rest-assured - 如何一次验证响应
问题描述
我想测试对 petstore.swagger.io 的 POST 请求的响应。我收到回复,为什么我不能使用路径“id”验证正文?我总是遇到错误,但正则表达式是正确的并且经过测试。
测试方法:
@Test
public void postPet() {
Pattern pt = Pattern.compile("<(\\d*)>");
Response response = given()
.contentType("application/json")
.body(jsonObject)
.when()
.post(String.format("https://petstore.swagger.io/v2/pet"))
.then()
.statusCode(200)
.log().body()
.and()
.assertThat()
.body("id", matchesPattern(pt))
错误:
java.lang.AssertionError: 1 expectation failed.
JSON path id doesn't match.
Expected: a string matching the pattern '<(\d*)>'
Actual: <9223372000666122518L>
响应正文是:
{
"id": 9223372000666122443,
"category": {
"id": 0,
"name": "string"
},
"name": "doggie",
"photoUrls": [
"string"
],
"tags": [
{
"id": 0,
"name": "string"
}
],
"status": "available"
}
id 字符串末尾的 L 是什么?在 swagger 中,没有 L 和 Postman 一样。我尝试了没有“<,>”的正则表达式。
解决方案
很清楚
你的
id
is9223372000666122518L
,L
意思是long
(数据类型)你使用正则表达式,但它只适用于
String
long
--> 比较vs时输入 mismachString
解决方案:
- 转换
id
为String
先断言
long id = ...log().body()
.extract().path("id");
assertThat(String.valueOf(id), Matchers.matchesPattern("\\d+"));
或者
- 编写一个自定义匹配器,来检查
isLong
,像这样在 Hamcrest 中有没有办法测试一个值是否为数字?
推荐阅读
- android - 数据库依赖(房间)有条件的 startDestination Android 导航
- python - 有没有办法减少从一维向量中查找前 k 个最大元素的索引所需的时间?
- python-3.x - 在单元测试中生成 EOF 错误,但如果我自己运行它则不会
- c# - 正确访问 System.Net.Http.DelegatingHandler 中的查询参数
- javascript - 如何使搜索过滤器和下拉过滤器一起工作Javascript
- java - 如何在不为 winappdriver 创建新会话的情况下为每个测试用例启动被测应用程序
- laravel - Laravel 自动获取和绑定每个视图的值
- r - R中的串扰 - 为什么过滤器不起作用?
- r - 使用两种宽度方案读取固定宽度文件
- python - 如何在python中取消堆叠具有多个索引的列?