How to check for size AND presence of some items in collections in hamcrest

mohamnag picture mohamnag · Oct 21, 2016 · Viewed 9k times · Source

I'm using Hamcrest 1.3 and trying to achieve the following in a more compact way.

Consider following test case:

@Test
public void testCase() throws Exception {

    Collection<String> strings = Arrays.asList(
        "string one",
        "string two",
        "string three"
    );

    // variant 1:
    assertThat(strings, hasSize(greaterThan(2)));
    assertThat(strings, hasItem(is("string two")));

    // variant 2:
    assertThat(strings, allOf(
        hasSize(greaterThan(2)),
        hasItem(is("string two"))
    ));
}

the goal here is to check for both size of collection AND some specific items to be included.

Where first variation is possible and accepted, it is not always that easy to do it, because maybe the collection is itself a result of some other operations and therefore it makes more sense to do all the operations on it using an allOf operation. Which is done in second variation above.

However containing the code of second variation will result in following compile time error:

error: no suitable method found for allOf(Matcher<Collection<? extends Object>>,Matcher<Iterable<? extends String>>)

Is there actually any specific way of testing for size AND items of a collection in Hamcrest using a single shot operation (like allOf)?

Answer

eee picture eee · Oct 23, 2016

I think the compiler is not able to sort out the generics. The following is working for me (JDK 8u102):

assertThat(strings, Matchers.<Collection<String>> allOf(
    hasSize(greaterThan(2)),
    hasItem(is("string two"))
));