Hamcrest closeTo在RestAssured.body中不起作用()

问题描述 投票:0回答:2

我有一个测试,我无法正确获得语法:

@Test
void statsTest() {
    given().queryParam("param", "ball")
            .when().get()
            .then().body("total", is(closeTo(10.0, 0.1*10.0))));
}

但是,即使符合条件,测试仍会失败:

java.lang.AssertionError: 1 expectation failed.
JSON path total doesn't match.
Expected: is a numeric value within <1.0> of <10.0>
Actual: 10

RestAssuredHamcrest的这个设置之前,我从未遇到类型问题。例如,类别的测试:body("total", greaterThan(9))工作正常,这意味着引擎盖下有一些类型的铸件。

我查看了文档,无法找到将body("total")的值转换为数值的方法。所以我怀疑这是一个错误,或者我在这里不了解一些东西。

这是JSON响应。我不得不将它剪辑成短片。希望这有效。

{
 "stats": {
 "totalHits": 1,
 "searchEngineTimeInMillis": 83,
 "searchEngineRoundTripTimeInMillis": 87,
 "searchProcessingTimeInMillis": 101
},
 "products": {
    "id": "total",
    "displayName": "Documents",
    "ball": 10}
}
groovy rest-assured hamcrest rest-assured-jsonpath
2个回答
1
投票

与键对应的键值对:响应中的“total”似乎是整数类型。因此需要检查具有整数边界的边界(1,10)。因此,您可以使用以下匹配器而不是使用closeTo匹配器。

allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)))

1
投票

我已经提出了另一种解决问题的方法,但方法略有不同。非常感谢那些用他们的代码样本填充网络的人。以下假设您已经设置了基础URIPATH。您可以使用get("/path...")在响应中更深入地添加路径。这个答案假定JSON类型的响应。

 private static Response getResponse(String paramName, String paramValue) {
    return given().queryParam(paramName, paramValue)
            .when().get();
}

 public static String getJsonValue(String jsonPath, String paramName, String paramValue) {
    Response response          = getResponse(paramName, paramValue);
    //response.getBody().prettyPrint();
    JsonPath jsonPathEvaluator = response.jsonPath();
    return jsonPathEvaluator.get(jsonPath).toString();
}

您只需打印返回值并将其转换为您需要的类型即可。然后测试看起来像这样:

 public static void checkIfNumberCloseToValue(String jsonPath,
                                             String paramName,
                                             String paramValue,
                                             Double error,
                                             Double expected) {
    Double value = Double.valueOf(Utils.getJsonValue(jsonPath, paramName, paramValue));
    double range = expected * error;
    assertThat(value, closeTo(expected, range));
}
© www.soinside.com 2019 - 2024. All rights reserved.