考虑以下代码:
public class DummyClass {
public List<? extends Number> dummyMethod() {
return new ArrayList<Integer>();
}
}
Run Code Online (Sandbox Code Playgroud)
public class DummyClassTest {
public void testMockitoWithGenerics() {
DummyClass dummyClass = Mockito.mock(DummyClass.class);
List<? extends Number> someList = new ArrayList<Integer>();
Mockito.when(dummyClass.dummyMethod()).thenReturn(someList); //Compiler complains about this
}
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨正在尝试存根行为的行dummyMethod().关于如何使用有界通配符返回类型的存根方法的任何指针?
我正在使用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第三方提供并且无法修改时,还有其他方法可以解决此问题吗?
我正在尝试编写单元测试,为此我正在为Mockito模拟写一个when语句,但我似乎无法通过eclipse来识别我的返回值是有效的.
这是我正在做的事情:
Class<?> userClass = User.class;
when(methodParameter.getParameterType()).thenReturn(userClass);
Run Code Online (Sandbox Code Playgroud)
返回类型.getParameterType()是Class<?>,所以我不明白为什么eclipse说,The method thenReturn(Class<capture#1-of ?>) in the type OngoingStubbing<Class<capture#1-of ?>> is not applicable for the arguments (Class<capture#2-of ?>).它提供了投射我的userClass,但这只是让一些乱码的东西eclipse说它需要再次施放(并且不能施放).
这只是Eclipse的一个问题,还是我做错了什么?