Search code examples
arraysgroovyjunit4hamcrest

How to assert that every item in collection is within range


I have a Groovy array that will get a set number of random Integer Values. And I want to assert that each item in the array has a value within the given range. I'm trying to use Hamcrest Matchers. So my test looks like this:

@Test
void testShouldReturnArrayOfStats(){
    def results = pg.rollStats()
    assertThat results, everyItem(both(greaterThan(0)).and(lessThanOrEqualTo(6)))
}

When I run the test I get an assertionError

java.lang.AssertionError: Expected: every item is (a value greater than <0> and a value less than or equal to <6>)
 but: was [<6>, <3>, <5>, <4>, <3>, <2>]

I've tried some variations of this but I'm not getting a passing test. just by looking at the "But:was" portion of the error I can seen that all 6 values meet the requirements, but the test still fails.

I've not used Groovy or Hamcrest for very long so I'm sure that I'm missing something. Thanks


Solution

  • Could you just use groovy?

    assert results.every { it in 1..6 }