继续来看看响应内容中的验证场景,这篇主要介绍如何使用java 8 lambda表达式在响应内容中断言的使用场景。然后来看看接口性能测试中响应时间丈量的方法。
1.正文属性断言场景
断言thumbnailUrl的值是不是这个图片中的地址。
2.使用匿名类
在java8之前,我们使用匿名类来实现。
/**
* 响应正文中的属性使用匿名类来断言
*/
@Test
public void testBodyParameterInResponse() {
given().
get("http://jsonplaceholder.typicode.com/photos/1/").
then().
body("thumbnailUrl", new ResponseAwareMatcher<Response>() {
public Matcher<?> matcher(Response response) throws Exception {
return equalTo("https://via.placeholder.com/150/92c952");
}
});
}
3.使用Java 8 lambda表达式
使用lambda表达式之后,代码更简洁。
/**
* 响应正文中的属性使用lambda表达式来断言
*/
@Test
public void testBodyParameterInResponse() {
given().
get("http://jsonplaceholder.typicode.com/photos/1/").
then().
body("thumbnailUrl", response -> equalTo("https://via.placeholder.com/150/92c952"));
given().
get("http://jsonplaceholder.typicode.com/photos/1/").
then().
body("thumbnailUrl", endsWith("92c952"));
}
4.cookie断言
由于每次浏览器访问都产生不同cookies,所以下面代码会运行失败。
/**
* test cookies in response
*/
@Test
public void testCookieInResponse() {
given().
get("http://jsonplaceholder.typicode.com/photos/1/").
then().
log().all().assertThat().cookie("__cfduid","d4eb57be1eeb2781c8f1f864b04c6ba741563591180");
}
实际代码中,cookies是通过代码去实时获取。cookies是在一定有效期内是同一个
5.响应时间丈量
有时候,我们需要做一些接口的性能测试,其中最大的性能指标就是接口的响应时间,那么我们来几个简单的练习,关于响应时间的
/**
* 响应时间
* 这个包含,http请求加响应处理时间 加上我们使用rest assured这个工具产生的时间之和
*/
@Test
public void testResponseTime() {
long t = given().get("http://jsonplaceholder.typicode.com/photos/").time();
System.out.println(t);
}
但是是毫秒,也就是2.6秒差不多这个请求。
如果想要直接输出单位是秒,而不是默认的毫秒,代码改成这样。
public void testResponseTime() {
long t = given().get("http://jsonplaceholder.typicode.com/photos/").timeIn(TimeUnit.SECONDS);
System.out.println(t);
}
如果我们要做这样场景,这个接口响应时间不能超过多少秒,可以这样写
@Test
public void testResponseTime() {
given().get("http://jsonplaceholder.typicode.com/photos/").then().time(lessThan(2000L));
}
上面代码就是超过2秒就会抛异常,小于2秒就执行通过。