如何在Java中使用rest assured对接口进行测试?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
假设你写了一个接口:lotto,访问路径是: http://localhost:8080/lotto
接口返回值:
{
"lotto":{
"lottoId":5,
"winning-numbers":[2,45,34,23,7,5,3],
"winners":[{
"winnerId":23,
"numbers":[2,45,34,23,3,5]
},{
"winnerId":54,
"numbers":[52,3,12,11,18,22]
}]
}
}
如何快速的验证接口是否返回正常值呢?
get("/lotto").then().body("lotto.winners.winnerId", hasItems(23, 54));
使用简单吧!
引入
不多说,直接maven的方式引入:注意,我直接按照默认的scope引入的,不是test;
主要引入以下2个依赖,原因如下:
rest-assured: 主要测试基本的http的rest风格接口,这个是最基础的依赖;
json-path: 主流的接口主要返回json,对接口进行测试用例测试,主要也是判断json返回某路径下的数据;
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>4.2.0</version>
</dependency>
然后你就可以愉快的编写测试用例,然后使用rest-assured进行接口测试了。
使用要点
先上简单代码吧!
先准备测试数据:
final TestCaseDataModel<LoginRestReq> testCaseDataModel = new TestCaseDataModel<>();
final LoginRestReq loginRestReq = LoginRestReq.builder()
.appId("2a6bf452219cfe44c7f78231e3c80a13072b6727")
.nonce("123456")
.timestamp(System.currentTimeMillis())
.userId("lxlifuchun")
.userName("李福春")
.build();
String appSecret = "91e47f584dae551170ade272b2c7a69f";
loginRestReq.setChecksum(SignUtils.generateCheckSum(loginRestReq.getAppId(), appSecret, loginRestReq.getTimestamp(), loginRestReq.getNonce()));
testCaseDataModel.setInputParam(loginRestReq);
ExpectModel expectModel = new ExpectModel();
expectModel.setPath("data.id");
expectModel.setMatcher(Matchers.lessThan(0));
testCaseDataModel.setExpectResult(Arrays.asList(expectModel));
RestAssured.baseURI = "https://rest-beta.xxx.com";
final ValidatableResponse validatableResponse = given().contentType(ContentType.JSON)
.header("requestId", UUID.randomUUID().toString())
.body(testCaseData.getInputParam()).
post("/user_service/user/login")
.then().contentType(ContentType.JSON);
for (Object obj : testCaseData.getExpectResult()) {
ExpectModel item = (ExpectModel) obj;
validatableResponse.body(item.getPath(), item.getMatcher());
}
做的事情很简单,就是拿一个登录接口来实际的试一下:
login接口接受一个json的参数,LoginRestReq对下转换之后得到;
然后返回数据,数据中有一个用户id,路径是 data.id,如果id大于0,标识登录操作成功,登录接口正常。
关于如何在Java中使用rest assured对接口进行测试问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。