Hamcrest Matchers包含匹配器列表 [英] Hamcrest Matchers contains with List of matchers
问题描述
我正在尝试使用 org.hamcrest.Matchers.contains(java.util.List< Matcher< ;? super E>>),但是编译器告诉我它无法解析该方法.
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)
我试图将第二个参数强制转换为Matcher< ;?超级列表< String>>
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?
推荐答案
问题是Arrays.asList(equalTo("foo"), equalTo("bar"));
将为您提供List<Matcher<String>>
类型,但您确实想要List<Matcher<? super String>>
.您必须明确指定类型:
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"))));
这篇关于Hamcrest Matchers包含匹配器列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!