简介
REST-assured是Github上一个开源项目
它的语法非常简洁,是一种专为测试 REST API 而设计的测试框架
基本使用
- Maven的pom.xml添加 REST-Assured 依赖坐标
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.2.0</version>
<scope>test</scope>
</dependency>
- 语法格式
given().
XXXX
when().
XXXX
then().
XXXX
类似于行为驱动开发(Behaviour Driven Development-BDD)中的定义的结构 Given-When-Then,Given: 在某场景下,When:发生什么事件,Then:产生了什么结果。而 REST-Assured 借鉴了这一套描述可以使 得语法更加简洁:
● given 设置测试预设(包括请求头、请求参数、请求体、cookies 等等)
● when 所要执行的操作(GET/POST 请求)
● then 解析结果、断言
get请求
- 直接在URL地址后面拼接参数
given().
when().
get("http://www.httpbin.org/get?wd="柠檬班").
then().
log().all();
- 通过queryParam方法添加参数
given().
queryParam("wd","柠檬班").
queryParam("ie","utf-8").
when().
get("https://www.baidu.com").
then().
log().all();
post请求
- form表单参数类型
given().
formParam("phone", "18700010002").
formParam("name", "zhangsan").
when().
post("http://www.httpbin.org/post").
then().
log().body();
- json参数类型
String jsonData = "{\"pwd\": \"1234567abc\",\"userName\": \"娃娃01\"}";
given().
body(jsonData).contentType(ContentType.JSON).
when().
post("http://www.httpbin.org/post").
then().
log().body();
- xml参数类型
String xmlData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<suite>\n" +
" <class>测试xml</class>\n" +
"</suite>";;
given().
body(xmlData).contentType(ContentType.XML).
when().
post("http://www.httpbin.org/post").
then().
log().body();
- 上传文件
传送大容量的数据到服务端时,通常使用 multipart 表单数据技术。rest-assured提供了一个叫做 multiPart 的方法可以让我们指定文件(file)、字节数组(byte-array)、输入流或者是上传文件
given().
multiPart(new File("E:\\测试用例\\前程贷业务用例.xlsx")).
when().
post("http://www.httpbin.org/post").
then().
log().body();
获取响应数据某字段值-Gpath解析
extract().response()
有时我们需要获取响应头中的一些信息,比如Token ,可以通过Gpath解析响应体某个值
String jsonData = "{\"pwd\": \"1234567abc\",\"userName\": \"娃娃01\"}";
Response res =
given().
body(jsonData).contentType(ContentType.JSON).
when().
post("http://www.httpbin.org/post").
then().
log().all().extract().response();
//获取接口响应时间
System.out.println(res.time());
//获取接口响应头某字段值
System.out.println(res.header("Content-Type"));
//获取接口响应体某字段值
System.out.println((String) res.jsonPath().get("json.pwd"));
提取json
res.jsonPath().get(“xxx.xxx.xxx”);
提取xml
res.xmlPath().get(“xxx.xxx.xxx”);
提取html
res.htmljsonPath().get(“xxx.xxx.xxx”);
提取hearder
res.header(“xxx.xxx”);
GPath可指定用例运行先后顺序:
方法1:可根据用例名的ACSII码大小进行编写—不推荐
方法2:使用pripority参数指定用例优先级:
@Test(pripority = xxx) xxx越小,用例的优先级越高
方法3:使用dependsOnMethons参数指定该用例依赖的其他用例:
@Test(dependsOnMethons = “所依赖的用例名”)