restassured:从具有指定值的json对象获取键值

0ejtzxu1  于 2021-07-03  发布在  Java
关注(0)|答案(3)|浏览(408)

在测试用例中,我使用以下响应执行调用:

[
    {
        "ourID": "770050010000000010",
        "date": "2019-03-07",
        "otherValue": null
    },
    {
        "ourID": "770050010000000020",
        "date": "2019-03-07",
        "otherValue": null
    }
]

测试由serenity执行,我使用restasured执行调用:

Response response = RestAssuredApiHelper.baseRestCall(headers, baseUrl, path)
                .body(requestBody)
                .post();

assertThat(response.getBody().jsonPath().get("$.[?(@.ourID=='770050010000000010')].date"), contains("2019-03-07"));

Assert不起作用,可能是因为restassured使用gpath而不是jsonpath,但是在我阅读的所有文档中都有这样的例子。我错过了什么?
我得到的错误是:

java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: unexpected token: [ @ line 1, column 29.
                            $.[?(@.meteringPointEANID=='770050010000000010')].energySource
                               ^

1 error
svmlkihl

svmlkihl1#

检查以下内容code:--(我相信json表达式是正确的,没有检查)

Object dateObject = JsonPath.parse(response.getBody().asString()).read("$.[?(@.ourID=='770050010000000010')].date");
String dateString = dataObject.toString();
assertThat(dateString, containsString("2019-03-07"));

聚甲醛dependency:---

<!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.1.0</version>
</dependency>
lfapxunr

lfapxunr2#

对restassured使用jsonpath的另一种方法是使用restassured的内置反序列化机制。
如果不知道对象的返回类型,可以检查以下内容:https://github.com/rest-assured/rest-assured/wiki/usage#deserialization-使用泛型
通用解决方案如下所示:

Response response = RestAssuredApiHelper.baseRestCall(headers, baseUrl, path)
                .body(requestBody)
                .post();

List<Map<String, Object>> objects =  response.getBody().as(new TypeRef<>() {});
Map<String, Object> singleObject = objects.stream().filter((Map<String, Object> object) -> object.get("ourID").equals("770050010000000010"))
                .peek(System.out::println)
                .findFirst().get();

System.out.println(singleObject.get("ourID")); // 770050010000000010

如果你知道响应对象是什么,那就更简单了:

List<YourResponseObject> yourResponseObjects = response.getBody().as(new TypeRef<>() {});
pb3s4cty

pb3s4cty3#

assertEquals(response.path("find {it.ourID == '770050010000000010'}.date"), "2019-03-07")

相关问题