3

The input:

  1. Collection with MyElement without equals method.
  2. A org.hamcrest.TypeSafeMatcher implementation, which matches element by some field.

The goal is make following statement compilable:

Collection<MyElement> elements = ...
Collection<TypeSafeMatchert> matchers = ...
assertThat(elements, Matchers.contains(matchers); //<error here

What have to use here? It wants me to Matcher<? super java.util.List<MyElement>> and told that actully I passed Matcher<java.lang.Iterable<? super java.util.List<MyElement>>>. So how to pass a Matcher Collection here?

There is a question about comparing collections with hamcrest, but there is no example with passing Matchers collection, not elements.

Community
  • 1
  • 1
Cherry
  • 31,309
  • 66
  • 224
  • 364
  • Possible duplicate of [Hamcrest compare collections](http://stackoverflow.com/questions/21624592/hamcrest-compare-collections) –  May 23 '16 at 05:18
  • very close, but there no answer with use Matcher instead of elements. :( – Cherry May 23 '16 at 05:20
  • try specifying types; like there: http://stackoverflow.com/questions/31103222/hamcrest-matchers-contains-with-list-of-matchers?rq=1 –  May 23 '16 at 05:28

2 Answers2

1

Instead of defining a Collection of TypeSafeMatchers, you need to define a:

    List<Matcher<? super MyElement>> matchers = ...;

This way, Hamcrest will know what you want.

Ruben
  • 3,986
  • 1
  • 21
  • 34
0

Use List instead of collection for the matchers, or convert it to array.

Hamcrest has following contains methods:

public static <E> org.hamcrest.Matcher<java.lang.Iterable<? extends E>> contains(org.hamcrest.Matcher<? super E>... itemMatchers)

public static <E> org.hamcrest.Matcher<java.lang.Iterable<? extends E>> contains(E... items)

public static <E> org.hamcrest.Matcher<java.lang.Iterable<? extends E>> contains(org.hamcrest.Matcher<? super E> itemMatcher)

public static <E> org.hamcrest.Matcher<java.lang.Iterable<? extends E>> contains(java.util.List<org.hamcrest.Matcher<? super E>> itemMatchers)

As you can see it handles Matchers only in case of a List or varags (but if you pass only one element then you need to convert it to array).

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115