使用Hamcrest库,我需要断言具有特定属性(java Bean)的对象列表与一组属性匹配。例如,如果我们有一个具有firstName,lastName和middleNameName属性的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
method。例如:
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.")))
)
));