如何放心地验证数组是否包含对象?

2022-09-03 02:00:30

例如,我有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));

有什么解决方案吗?
提前感谢您的帮助!


答案 1

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

因此,您可以执行以下操作:

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));

答案 2

这对我有用:

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