本文共 2577 字,大约阅读时间需要 8 分钟。
继续来做RestAssured的基本功能练习,先来看看root()这个方法的使用效果。
1.root()
作用:设置一个body断言开始的base路径,后面boday断言中可以不写完整路径,只写当前路径。
例如,加入这里有这么一个请求的响应是这样。
{ "RestResponse":{ "message" :"abcddd", "result":{ "name":"tom", "age" : 18, "gender": "man" } }}
场景1:不使用root()
@Test public void testWithoutRoot() { given(). get("xxxxxxxurlxxxxx"). then(). body("RestResponse.result.name", is("tom")). body("RestResponse.result.age", is("18")). body("RestResponse.result.gender", is("man")); }
场景2:使用root()
@Test public void testWithoutRoot() { given(). get("xxxxxxxurlxxxxx"). then(). root("RestResponse.result"). body("name", is("tom")). body("age", is("18")). body("gender", is("man")); }
了解以下就行,这个root()方法在Rest Assured 4.0.0中被标注不推荐使用。
2.一个post请求举例
demo:
/** * 一个post请求举类 */ @Test public void testAPostMethod() { given(). param("name", "Anthony123"). param("job", "tester"). header("Content-Type", "text/html"). when(). post("https://reqres.in/api/users"). then().statusCode(201).log().all(); }
得到结果
[RemoteTestNG] detected TestNG version 6.14.3HTTP/1.1 201 CreatedDate: Mon, 22 Jul 2019 13:38:13 GMTContent-Type: application/json; charset=utf-8Content-Length: 51Connection: keep-aliveSet-Cookie: __cfduid=d42f5cc223108aebf6472008642b439371563802693; expires=Tue, 21-Jul-20 13:38:13 GMT; path=/; domain=.reqres.in; HttpOnly; SecureX-Powered-By: ExpressAccess-Control-Allow-Origin: *Etag: W/"33-Kx6moXiZomfqu06UYcrOOzUNtH8"Via: 1.1 vegurExpect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"Server: cloudflareCF-RAY: 4fa5d0519cfad32a-LAX{ "id": "371", "createdAt": "2019-07-22T13:38:13.630Z"}PASSED: testAPostMethod
3.以字符串类型拿到全部响应
有时候我们需要对整体的响应输出进行字符串的操作,这个前提就是我们需要把响应对象转换成字符串,一般响应格式有JSON和XML。
/** * 以字符串的方式拿到全部响应 */ @Test public void getResponseAsString() { String responseAsString = get("https://reqres.in/api/users/2").asString(); System.out.println("The Response: \n\n" + responseAsString); }
运行结果:
The Response: {"data":{"id":2,"email":"janet.weaver@reqres.in","first_name":"Janet","last_name":"Weaver","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"}}PASSED: getResponseAsString
4.以输入流拿到全部响应
直接来看把响应内容转换成inputStream的方法
/** * 以InputStream方式拿到响应对象 * @throws IOException */ @Test public void testGetResponseAsInputStream() throws IOException { InputStream responseAsInputStream = get("https://reqres.in/api/users/2").asInputStream(); System.out.println("The Response: \n\n" + responseAsInputStream.toString().length()); responseAsInputStream.close(); }
输出结果是:流的长度为 84
转载地址:http://ojows.baihongyu.com/