hardayal / hamcrest

Automatically exported from code.google.com/p/hamcrest
0 stars 0 forks source link

All-Satisfy Matcher #169

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
It's easy to make assertions that an item in an Iterable satisfies or doesn't 
satisfy a condition by using hasItem and not.

// Any Satisfy
Assert.assertThat(
  Arrays.<Number>asList(1, 2.0),
  hasItem(Matchers.<Integer>instanceOf(Integer.class)));

// None Satisfy
Assert.assertThat(
  Arrays.<Number>asList(1.0, 2.0),
  not(hasItem(Matchers.<Integer>instanceOf(Integer.class))));

I couldn't find a matcher that asserts that all items in an iterable satisfy 
the matcher. You can still use hasItem and not, but the nesting is deep.
// All Satisfy
Assert.assertThat(
  Arrays.<Number>asList(1.0, 2.0),
  not(hasItem(not(Matchers.<Integer>instanceOf(Double.class)))));

This works, but the error message is confusing.

java.lang.AssertionError: 
Expected: not a collection containing not an instance of java.lang.Double
     got: <[1, 2.0]>

I'd recommend adding a matcher that returns true when all items in the iterable 
satisfy the nested matcher.

Original issue reported on code.google.com by motlin on 26 Dec 2011 at 9:48

GoogleCodeExporter commented 8 years ago
You can use everyItem(matcher) for this:

    Assert.assertThat(
      Arrays.<Number>asList(1, 2.0),
      everyItem(Matchers.<Integer>instanceOf(Integer.class)));

I haven't used the Java version in a while, but do you really need the 
"Matchers.<Integer>" part?

Original comment by dharkn...@gmail.com on 20 Jan 2012 at 6:40