java - 如何使 JUnit assertThat() 使用下限通配符?

标签 java generics junit assertthat

最初,我有这段生产代码:

interface ActionSequence {
   public List<Actions> getActions();

我用这样的东西测试了实现该接口(interface)的类:

assertThat(sequenceUnderTest.getActions(), is(Arrays.asList(action1, action2));

然后我认为将生产接口(interface)更改为:

public List<? extends Action> getActions() {

(允许我返回 Action 的子类列表)。

但是现在 eclipse 告诉我:

The method assertThat(T, Matcher<? super T>) in the type Assert is not applicable for the arguments (List<capture#1-of ? extends Action>, Matcher<List<Action>>)

我想:当我更改实现 ActionInterface 的

@Override
public List<SomeSubClassOfAction> getActions()

(而不是保留通配符)...然后一切正常。但是为什么?

最佳答案

Arrays.asList(action1, action2)将返回 List<Action> . is(Arrays.asList(action1, action2))因此将返回 Matcher<List<Action>> .

assertThat 具有以下签名:

assertThat(T actual, Matcher<T> matcher)

因此 assertThat 在您的案例中需要以下参数:

assertThat(List<Action>, Matcher<List<Action>>)

但是你的第一个参数是List<? extends Action> 还有一个 List<Action>List<? extends Action> 完全不同. 例如,您不能将 Action 元素放入 List<SomeSubClassOfAction> 中. 这就是为什么这行不通的原因。

有关详细信息,请参阅 Angelika Langer 的优秀网站:http://www.angelikalanger.com/GenericsFAQ/FAQSections/Index.html

关于java - 如何使 JUnit assertThat() 使用下限通配符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34811617/

相关文章:

java - Spring 启动: Inject beans from tests into web environment

java - 如何在反序列化文档时忽略未使用的 XML 元素?

java - 在桌面上运行 Java 程序

typescript - 命名泛型函数的返回类型

c# - 通用接口(interface),通用接口(interface)与泛型

junit - 我应该拆分方法以便在 JUnit 中重用吗?

java - 在 java 中读取 DataInputStream 中的整数用户输入?

java - Java 中的哈希表手动冲突处理

Typescript:键与值类型相同的映射,不限制键的类型

java - JUnit 参数化数据注入(inject)