How to check the size and presence of some items in collections in hamcrest

I am using Hamcrest 1.3 and trying to do the following in a more compact way.

Consider the 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 both the size of the collection and some specific elements that will be included.

If the first variation is possible and accepted, it is not always so simple to do, because perhaps the collection itself is the result of some other operations, and therefore it makes sense to do all operations on it using the allOf operation. This is done in the second version above.

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

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

Is there any specific testing method for size items and collection items in Hamcrest using a single shot operation (like allOf )?

+5
source share
2 answers

I think the compiler cannot figure out generics. Works for me (JDK 8u102):

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

Guess: you won’t get there using existing sockets.

But writing your own interlocutor ... takes only a few minutes, as soon as you understand how everything is combined.

Perhaps you check another answer of mine; where I give a complete example of how you can write your own interlocutor. Then it took me 15 minutes; although I’ve never written custom mappings before.

0
source

Source: https://habr.com/ru/post/1258605/


All Articles