最初,我有这段生产代码:
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/