使用Hamcrest everyItem()的编译错误 [英] Compilation error using Hamcrest everyItem()
问题描述
我试图在Hamcrest的everyItem()
上使用hasKey()
,但是出现以下编译错误:
I'm trying to use hasKey()
on everyItem()
in Hamcrest but I am getting the following compilation error:
error: no suitable method found for assertThat(List<Map<String,Object>>,Matcher<Iterable<Map<? extends String,?>>>)
assertThat(data, everyItem(hasKey("index")));
^
method Assert.<T#1>assertThat(T#1,Matcher<? super T#1>) is not applicable
(actual argument Matcher<Iterable<Map<? extends String,?>>> cannot be converted to Matcher<? super List<Map<String,Object>>> by method invocation conversion)
method Assert.<T#2>assertThat(String,T#2,Matcher<? super T#2>) is not applicable
(cannot instantiate from arguments because actual and formal argument lists differ in length)
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>assertThat(T#1,Matcher<? super T#1>)
T#2 extends Object declared in method <T#2>assertThat(String,T#2,Matcher<? super T#2>)
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
这是一个简单的JUnit测试,它会重新创建错误:
Here is a simple JUnit test that recreates the error:
package test;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.collection.IsMapContaining.hasKey;
import static org.hamcrest.core.Every.everyItem;
import static org.junit.Assert.assertThat;
public class Test {
@Test
public void test(){
List<Map<String, Object>> data = new ArrayList<>();
Map<String,Object> element = new HashMap<>();
element.put("index", 1);
data.add(element);
assertThat(data, everyItem(hasKey("index")));
}
}
- Java 1.7
- Hamcrest 1.3
- JUnit 4.11
有人知道如何解决此编译错误吗?
Does anyone know how to resolve this compilation error?
推荐答案
这是嵌套泛型的情况.
data
当前被声明为List<Map<String, Object>>
,而 被推断为返回了Matcher<Iterable<Map<? extends String, ?>>>
.
data
is currently declared as a List<Map<String, Object>>
, while everyItem(hasKey("index"))
is inferred as returning a Matcher<Iterable<Map<? extends String, ?>>>
.
如编译错误消息所述
类型为
Assert
的方法assertThat(T, Matcher<? super T>)
不是 适用于参数(List<Map<String,Object>>, Matcher<Iterable<Map<? extends String,?>>>
)
The method
assertThat(T, Matcher<? super T>)
in the typeAssert
is not applicable for the arguments (List<Map<String,Object>>, Matcher<Iterable<Map<? extends String,?>>>
)
这可以归结为 hasKey
的返回类型为Map<? extends T, ?
而不是Map<T, ?>
,但这可能是有充分理由的.
This boils down to hasKey
having a return type of Map<? extends T, ?
rather than Map<T, ?>
, but there's probably a good reason for that.
幸运的是,您的代码非常简单,可以将data
声明为
Fortunately, your code is simple enough that you can declare data
as
List<Map<? extends String, ?>> data = new ArrayList<>();
并编译代码.
这篇关于使用Hamcrest everyItem()的编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!