Java 使用匹配器断言集合包含具有相同属性的2个对象

Java 使用匹配器断言集合包含具有相同属性的2个对象,java,testing,junit,junit4,hamcrest,Java,Testing,Junit,Junit4,Hamcrest,我有以下场景,我想测试someFunction(): 如果要验证每个项目是否都具有该属性,并且恰好有两个项目,请使用和: 如果要专门测试集合的内容,但恰好两个预期项相同,请使用变量和: Matcher m=hasProperty(“property”,is(propertyIWantToTest)); (对象,包含任意顺序(m,m))的资产; Collection<MyObject> objects = someFunction(someInput); assertThat(obj

我有以下场景,我想测试someFunction():


如果要验证每个项目是否都具有该属性,并且恰好有两个项目,请使用和:

如果要专门测试集合的内容,但恰好两个预期项相同,请使用变量和:

Matcher m=hasProperty(“property”,is(propertyIWantToTest));
(对象,包含任意顺序(m,m))的资产;
Collection<MyObject> objects = someFunction(someInput);
assertThat(objects , contains(hasProperty("property", is(propertyIWantToTest))));
assertThat(objects , contains(exactlyTwoTimes(hasProperty("property", is(propertyIWantToTest)))));
assertThat(objects, everyItem(hasProperty("property", is(propertyIWantToTest))));
assertThat(objects, hasSize(2));
Matcher<MyObject> m = hasProperty("property", is(propertyIWantToTest));
assertThat(objects, containsInAnyOrder(m, m));