Hamcrest Matchers contains with List of matchers

烂漫一生 提交于 2019-12-24 14:48:20

问题


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"))));


来源:https://stackoverflow.com/questions/31103222/hamcrest-matchers-contains-with-list-of-matchers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!