如何验证该数组包含放心的对象?

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

例如,我有JSON作为回应:

[{"id":1,"name":"text"},{"id":2,"name":"text"}]}

我想验证响应是否包含自定义对象。例如:

Person(id=1, name=text)

我找到了解决方案

Person[] persons = response.as(Person[].class);
assertThat(person, IsArrayContaining.hasItemInArray(expectedPerson));

我想要这样的东西:

response.then().assertThat().body(IsArrayContaining.hasItemInArray(object));

这有什么解决方案吗? 在此先感谢您的帮助!

java arrays rest-assured hamcrest
2个回答
1
投票

body()方法接受路径和Hamcrest匹配器(参见javadocs)。

所以,你可以这样做:

response.then().assertThat().body("$", customMatcher);

例如:

// 'expected' is the serialised form of your Person
// this is a crude way of creating that serialised form
// you'll probably use whatever JSON de/serialisaiotn library is in use in your project 
Map<String, Object> expected = new HashMap<String, Object>();
expected.put("id", 1);
expected.put("name", "text");

response.then().assertThat().body("$", Matchers.hasItem(expected));

0
投票

在这种情况下,您还可以使用json模式验证。通过使用它,我们不需要为JSON元素设置单独的规则。

看看Rest assured schema validation

get("/products").then().assertThat().body(matchesJsonSchemaInClasspath("products-schema.json"));
© www.soinside.com 2019 - 2024. All rights reserved.