The matcher IsIterableContainingInAnyOrder
has two overloads for the static factory method containsInAnyOrder
(both have the return type Matcher<java.lang.Iterable<? extends T>>
):
containsInAnyOrder(java.util.Collection<Matcher<? super T>> itemMatchers)
containsInAnyOrder(Matcher<? super T>... itemMatchers)
Now consider the following program:
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import org.junit.Test;
public class SomeTest {
@SuppressWarnings("unchecked")
@Test
public void foo() {
assertThat(Arrays.asList("foo","bar"),
containsInAnyOrder(equalTo("foo"), equalTo("bar")));
}
}
When executing this as a JUnit test, it passes, as expected. It uses the second overload of containsInAnyOrder
shown above.
Now, when I change the assertion to this (which exactly matches the example given in the documentation of the first overload):
assertThat(Arrays.asList("foo","bar"),
containsInAnyOrder(Arrays.asList(equalTo("foo"), equalTo("bar"))));
^^^^^^^^^^^^^^
it doesn't compile anymore, because now the compiler infers the return type of containsInAnyOrder
to be
Matcher<Iterable<? extends List<Matcher<String>>>>
It seems like the compiler still chooses the second overload. If it used the first one, the example should work. Why does it behave like this? How can I make this work?
I am using Hamcrest 1.3 and Oracle Java 1.7.
It actually matches both overloaded methods. I'm not sure why exactly the first one is chosen, but you can provide a hint to make it choose the correct method.
By casting the argument to
Collection
:or by specifying the generic type T as
<String>
(don't work with static import, though):