我正在尝试使用org.hamcrest.Matchers.contains(java.util.List<Matcher<? super E>>),但编译器告诉我它无法解析该方法。
我甚至尝试过Hamcrest here给出的示例,但我得到了相同的编译错误:
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)
我试图将第二个参数转换为Matcher&lt;?超级列表&lt; String&gt;&gt;
assertThat(Arrays.asList("foo", "bar"), (Matcher<? super List<String>>)contains(Arrays.asList(equalTo("foo"), equalTo("bar"))));
但后来又出现了另一个编译错误:
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>>>>
有没有办法正确使用这种方法?
答案 0 :(得分:3)
问题是Arrays.asList(equalTo("foo"), equalTo("bar"));
会为您提供List<Matcher<String>>
类型,但您确实需要List<Matcher<? super String>>
。您必须明确指定类型:
assertThat(str,
contains(Arrays.<Matcher<? super String>>asList(
equalTo("foo"),
equalTo("bar"))));