【发布时间】:2013-04-11 07:21:08
【问题描述】:
我使用的是 mockito 1.9.5。 我有以下代码:
public class ClassA {
public List<? extends MyInterface> getMyInterfaces() {
return null;
}
public static void testMock() {
List<MyInterface> interfaces = new ArrayList<>();
ClassA classAMock = mock(ClassA.class);
when(classAMock.getMyInterfaces()).thenReturn(interfaces);
}
thenReturn(interfaces) 出现编译错误:
"The method thenReturn(List<capture#1-of ? extends MyInterface>) in the type
OngoingStubbing<List<capture#1-of ? extends MyInterface>> is not applicable for the arguments
(List<MyInterface>)"
但是,当我使用 mockito 的 thenAnswer 方法时,我没有收到错误消息。谁能告诉我发生了什么事?为什么我在使用thenReturn 方法时会收到错误消息?
当ClassA由第三方提供且无法修改时,有没有其他方法可以解决这个问题?
【问题讨论】:
-
getMyInterfaces的返回类型中不应包含通配符。这不是一个好的做法,因为该 api 的客户端必须处理他们不知道的通配符。 -
我不控制这个 API。它是由第 3 方提供的。
-
@SpaceTrucker 我认为拥有像
List<? extends MyInterface>这样的返回类型是非常明智的做法。这意味着您(作为方法调用者)可以将MyInterface对象从列表中取出,但您不能将任何内容放入其中。