Hamcrest Matchers contains with List of matchers

2019-08-10 10:57发布

问题:

I am trying to use org.hamcrest.Matchers.contains(java.util.List<Matcher<? super E>>), but the compiler tells me that it cannot resolve the method.

I even tried the example given by Hamcrest here, but I get the same compilation error:

assertThat(Arrays.asList("foo", "bar"), contains(Arrays.asList(equalTo("foo"), equalTo("bar"))));

Error:(13, 9) java: no suitable method found for assertThat(java.util.List<java.lang.String>,org.hamcrest.Matcher<java.lang.Iterable<? extends java.util.List<org.hamcrest.Matcher<java.lang.String>>>>)
method org.hamcrest.MatcherAssert.<T>assertThat(T,org.hamcrest.Matcher<? super T>) is not applicable
  (actual argument org.hamcrest.Matcher<java.lang.Iterable<? extends java.util.List<org.hamcrest.Matcher<java.lang.String>>>> cannot be converted to org.hamcrest.Matcher<? super java.util.List<java.lang.String>> by method invocation conversion)
method org.hamcrest.MatcherAssert.<T>assertThat(java.lang.String,T,org.hamcrest.Matcher<? super T>) is not applicable
  (cannot instantiate from arguments because actual and formal argument lists differ in length)
method org.hamcrest.MatcherAssert.assertThat(java.lang.String,boolean) is not applicable
  (actual argument java.util.List<java.lang.String> cannot be converted to java.lang.String by method invocation conversion)

I tried to cast the second argument to Matcher<? super List<String>>

assertThat(Arrays.asList("foo", "bar"), (Matcher<? super List<String>>)contains(Arrays.asList(equalTo("foo"), equalTo("bar"))));

but then I get another compilation error:

Error:(16, 88) java: inconvertible types  
required: org.hamcrest.Matcher<? super java.util.List<java.lang.String>> 
found:    org.hamcrest.Matcher<java.lang.Iterable<? extends java.util.List<org.hamcrest.Matcher<java.lang.String>>>>

Is there a way to properly use this method?

回答1:

The problem is that Arrays.asList(equalTo("foo"), equalTo("bar")); will give you the type List<Matcher<String>>, but you really want List<Matcher<? super String>>. You have to explicitly specify the type:

assertThat(str, 
    contains(Arrays.<Matcher<? super String>>asList(
        equalTo("foo"), 
        equalTo("bar"))));