首页 > 解决方案 > 如何一次验证响应

问题描述

我想测试对 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 一样。我尝试了没有“<,>”的正则表达式。

标签: rest-assured

解决方案


很清楚

  • 你的idis 9223372000666122518LL意思是long(数据类型)

  • 你使用正则表达式,但它只适用于String

long--> 比较vs时输入 mismachString

解决方案:

  1. 转换idString先断言
long id = ...log().body()
                .extract().path("id");

assertThat(String.valueOf(id), Matchers.matchesPattern("\\d+"));

或者

  1. 编写一个自定义匹配器,来检查isLong,像这样在 Hamcrest 中有没有办法测试一个值是否为数字?

推荐阅读