相关疑难解决方法(0)

使用mockito模拟使用通配符返回泛型的方法

我正在使用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);      
}
Run Code Online (Sandbox Code Playgroud)

我得到一个编译错误的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>)"
Run Code Online (Sandbox Code Playgroud)

但是,当我使用thenAnswermockito 的方法时,我没有得到错误.谁能告诉我发生了什么事?使用该thenReturn方法时为什么会出现错误?当ClassA第三方提供并且无法修改时,还有其他方法可以解决此问题吗?

java generics mockito

46
推荐指数
2
解决办法
2万
查看次数

带有泛型的mock方法,并以返回类型扩展

是否可以使用签名模拟(使用mockito)方法Set<? extends Car> getCars()而不使用supress警告?我试过了:

XXX cars = xxx;
when(owner.getCars()).thenReturn(cars);
Run Code Online (Sandbox Code Playgroud)

但不管我怎么声明cars我总是得到一个编译错误.例如,当我宣布这样的时候

Set<? extends Car> cars = xxx
Run Code Online (Sandbox Code Playgroud)

我得到标准的通用/ mockito编译错误

The method thenReturn(Set<capture#1-of ? extends Car>) in the type OngoingStubbing<Set<capture#1-of ? extends Car>> is not applicable for the arguments (Set<capture#2-of ? extends Car>)
Run Code Online (Sandbox Code Playgroud)

java generics mockito

15
推荐指数
1
解决办法
1万
查看次数

标签 统计

generics ×2

java ×2

mockito ×2