Java 如何用rest-assured验证数组包含对象?

Java 如何用rest-assured验证数组包含对象?,java,arrays,rest-assured,hamcrest,Java,Arrays,Rest Assured,Hamcrest,例如,我有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)); 我想要这样的东西: r

例如,我有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));
有什么解决办法吗?
提前感谢您的帮助

body()方法接受路径和Hamcrest匹配器(请参阅)

所以,你可以这样做:

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));
/“expected”是您个人的序列化形式
//这是一种创建序列化表单的粗糙方法
//您可能会使用项目中使用的JSON de/serialisaiotn库
Map expected=新的HashMap();
预期。投入(“id”,1);
预期。放入(“名称”、“文本”);
response.then().assertThat().body(“$”,Matchers.hasItem(预期));

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

看看

这对我很有用:

body("path.to.array",
    hasItem(
          allOf(
              hasEntry("firstName", "test"),
              hasEntry("lastName", "test")
          )
    )
)

你检查过他们关于匿名数组的文档了吗?我使用JSON模式进行验证,但在当前情况下,我想验证数组是否包含对象,这意味着对象值对我来说很重要。据我所知—“matchesJsonSchemaInClasspath”适用于JSON对象,但不适用于JSON数组。如果你知道一种简单的方法来让数组工作,我很乐意去看看。
body("path.to.array",
    hasItem(
          allOf(
              hasEntry("firstName", "test"),
              hasEntry("lastName", "test")
          )
    )
)