![](/img/trans.png)
[英]How to use AssertThat to check the property value of objects in a list?
[英]How to assertThat a list of objects has a set of properties with certain values
使用 Hamcrest 库,我需要断言具有特定属性(java bean)的对象列表与一组属性匹配。 例如,如果我们有一个带有 firstName、lastName 和 middleName 属性的 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.")))
)
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.