接口自动化基本请求
一.引入依赖-REST-assured
REST-assured是Github上一个开源项目
它的语法非常简洁,是一种专为测试 REST API 而设计的测试框架
Maven的pom.xml添加 REST-Assured 依赖坐标
io.rest-assured
rest-assured
4.2.0
test
二.请求语法
基本语法
Response response=
given().
xxx
when().
xxx
then().
xxx
given 设置测试预设(包括请求头、请求参数、请求体、cookies 等等)
when 所要执行的操作(GET/POST 请求)
then 解析结果、断言
1.请求头
在请求语法中,请求头可以一个个写(header("headkey","headvalue")),也可以把请求头全部添加到hashmap里,请求中就只要加入headermap,如下:
HashMapheadermap=new HashMap<>();
headermap.put("Content-Type","application/json;charset=UTF-8");
headermap.put("uid","1977");
headermap.put("platform","4");
headermap.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36");
headermap.put("deviceInfo","0854af77-58a1-4657-a497-a435ca4ebc01");
2.请求方法
(1)get请求
1)直接在url后面拼接参数
Response response= given(). headers(headermap). when(). get("http://host:port/path?xx=aa&yy=bb"). then(). log().body().extract().response();2)通过queryparam添加参数
Response response= given(). queryParam("xx","aa").queryParam("password","123456").headers(headermap). when(). get("http://host:port/path"). then(). log().body().extract().response();(2)post请求
1)form表单参数类型
headermap里的content-type为application/x-www-form-urlencoded
Response response= given(). formParam("mobilephone","13323234545").formParam("password","123456").headers(headermap). when(). post("url"). then(). log().body().extract().response();2)json参数类型
headermap的content-type为application/json
String jsonData = "{\"mobilephone\":\"13323234545\",\"password\":\"234545\"}"; Response response= given(). body(jsonData).headers(headermap). when(). post("url"). then(). log().body().extract().response();3)xml参数类型
headermap的content-type为text/xml
String xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "4)上传文件
headermap的content-type为multipart/form-data
Response response= given(). multiPart(new File("D:\\match.png")).headers(headermap). when(). post("url"). then(). log().body().extract().response();3.获取响应
有时我们需要获取响应头中的一些信息
//获取接口请求响应时间 System.out.println(response.time()); //获取响应头信息 System.out.println(response.getHeader("Content-Type")); //获取响应体信息(Json格式) System.out.println(response.jsonPath().get("lotto.lottoId"));三.响应体数据提取
1.json响应体数据提取
response.jsonPath().get("xxx.xxx.xxx")
案例:
usertoken=loginres.jsonPath().getString("data.loginData.userToken");
2.xml响应体数据提取
response.xmlPath().get("xxx.xxx.xxx")
案例:
String shuxing=xmlres.xmlPath().get("slideshow.slide[0].@type"); //获取第一个slide标签的type属性值 String title=xmlres.xmlPath().get("slideshow.slide[1].title"); //获取第二个slide标签的title文本值
(1)在xml中有多个slide,要选择第n个slide,在slide后面加上[n-1];
(2)标签.@属性名:在html中获取属性值
(3)标签.标签:获取的是标签包含的文本值
3.html响应体数据提取
response.htmlPath().get("xxx.xxx.xxx")
案例:
String shuxing=htmlresponse.htmlPath().get("html.head.meta[0].@http-equiv"); String title=htmlresponse.htmlPath().get("html.head.title");
(1)在html中有多个meta,要选择第n个mata,在meta后面加上[n-1];
(2)标签.@属性名:在html中获取属性值
(3)标签.标签:获取的是标签包含的文本值