gpt4 book ai didi

java - 使用 Hamcrest everyItem() 的编译错误

转载 作者:行者123 更新时间:2023-11-30 08:06:43 26 4
gpt4 key购买 nike

我正在尝试在 Hamcrest 的 everyItem() 上使用 hasKey(),但出现以下编译错误:

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 测试:

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

有谁知道如何解决这个编译错误?

最佳答案

这是嵌套泛型的一个例子。

data当前声明为 List<Map<String, Object>> , 而 everyItem(hasKey("index")) 被推断为返回 Matcher<Iterable<Map<? extends String, ?>>> .

如编译错误信息所述

The method assertThat(T, Matcher<? super T>) in the type Assert is not applicable for the arguments (List<Map<String,Object>>,
Matcher<Iterable<Map<? extends String,?>>>
)

归结为 hasKey 返回类型为 Map<? extends T, ?而不是 Map<T, ?> ,但这可能是有充分理由的。

幸运的是,您的代码足够简单,您可以声明 data作为

List<Map<? extends String, ?>> data = new ArrayList<>();

并编译代码。

关于java - 使用 Hamcrest everyItem() 的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34169380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com