如何断言对象列表具有一组具有特定值的属性



使用 Hamcrest 库,我需要断言具有特定属性(java bean(的对象列表与一组属性匹配。例如,如果我们有一个具有名字、姓氏和中间名属性的 Person 对象列表,我已经尝试了以下方法:

assertThat(personObjectList, either(contains(
hasProperty("firstName", is("Bob")),
hasProperty("lastName", is("Smith")),
hasProperty("middleName", is("R.")))
.or(contains(
hasProperty("firstName", is("Alex")),
hasProperty("lastName", is("Black")),
hasProperty("middleName", is("T."))));

但是在执行中没有获得对象的属性,我只是与对象 T 进行比较,输出如下:

但是:是Person@7bd7c4cf,是Person@5b9df3b3

有没有办法使用Hamcrest完成我在这里尝试做的事情?这在执行单个包含时有效,但是当使用 any(( 执行两个包含时,我会收到上面的输出。

您可以使用anyOf方法。例如:

List<Person> persins = Arrays.asList( new Person("Bob", "Smith", "R."));
assertThat(persons, contains(anyOf(
sameProprtyValues(new Person("Bob", "Smith", "R.")),
sameProprtyValues(new Person("Alex", "Black", "T.")) 
));

如果要使用多个属性,则应尝试:

assertThat(persons, contains(
either(
both(hasProperty("firstName", is("Bob")))
.and(hasProperty("lastName", is("Smith")))
.and(hasProperty("middleName", is("R.")))
).or(
both(hasProperty("firstName", is("Alex")))
.and(hasProperty("lastName", is("Black")))
.and(hasProperty("middleName", is("T.")))
)
));

最新更新