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

yar*_*fed 8 java arrays hamcrest rest-assured

例如,我有JSON作为响应:

[{"id":1,"name":"text"},{"id":2,"name":"text"}]}
Run Code Online (Sandbox Code Playgroud)

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

Person(id=1, name=text)
Run Code Online (Sandbox Code Playgroud)

我找到了解决方案:

Person[] persons = response.as(Person[].class);
assertThat(person, IsArrayContaining.hasItemInArray(expectedPerson));
Run Code Online (Sandbox Code Playgroud)

我想要这样的东西:

response.then().assertThat().body(IsArrayContaining.hasItemInArray(object));
Run Code Online (Sandbox Code Playgroud)

有什么解决办法吗?
在此先感谢您的帮助!

小智 13

这对我有用:

body("path.to.array",
    hasItem(
          allOf(
              hasEntry("firstName", "test"),
              hasEntry("lastName", "test")
          )
    )
)
Run Code Online (Sandbox Code Playgroud)


gly*_*ing 8

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

所以,你可以这样做:

response.then().assertThat().body("$", customMatcher);
Run Code Online (Sandbox Code Playgroud)

例如:

// '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));
Run Code Online (Sandbox Code Playgroud)