0

I have the following scenario, where I want to test someFunction():

Collection<MyObject> objects = someFunction(someInput);
assertThat(objects , contains(hasProperty("property", is(propertyIWantToTest))));

This works fine if Collection<MyObject> objects should have just 1 MyObject object according to someInput which is passed to someFunction(). However, there are some cases for someInput that the Collection<MyObject> objects should have 2 or more MyObject object containg the same propertyIWantToTest object. Is there a way to use Hamcrest matchers to test that?

Here's something closer to what I'm willing to achieve:

assertThat(objects , contains(exactlyTwoTimes(hasProperty("property", is(propertyIWantToTest)))));
fvdalcin
  • 1,047
  • 1
  • 8
  • 26

1 Answers1

2

If you want to verify that every item has that property, and that there are exactly two items, then use everyItem and hasSize:

assertThat(objects, everyItem(hasProperty("property", is(propertyIWantToTest))));
assertThat(objects, hasSize(2));

If you want to specifically test the contents of the collection, but it just so happens that both expected items are the same, use a variable and containsInAnyOrder:

Matcher<MyObject> m = hasProperty("property", is(propertyIWantToTest));
assertThat(objects, containsInAnyOrder(m, m));
Joe
  • 29,416
  • 12
  • 68
  • 88