我正在尝试编写一个单元测试,为此我正在为一个Mockito mock编写一个when语句,但是我似乎无法让eclipse识别我的返回值是有效的。
这就是我要做的:
Class<?> userClass = User.class;
when(methodParameter.getParameterType()).thenReturn(userClass);
.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的问题,还是我做错了什么?
发布于 2013-08-15 05:43:39
此外,解决此问题的一种更简洁的方法是使用do语法,而不是when。
doReturn(User.class).when(methodParameter).getParameterType();
发布于 2013-08-15 08:59:24
Class<?> userClass = User.class;
OngoingStubbing<Class<?>> ongoingStubbing = Mockito.when(methodParameter.getParameterType());
ongoingStubbing.thenReturn(userClass);
Mockito.when
返回的OngoingStubbing<Class<?>>
与ongoingStubbing
的类型不同,因为每个“?”通配符可以绑定到不同的类型。
要使类型匹配,需要显式指定type参数:
Class<?> userClass = User.class;
Mockito.<Class<?>>when(methodParameter.getParameterType()).thenReturn(userClass);
发布于 2013-06-03 12:56:17
我不知道你为什么会得到这个错误。它一定与返回Class<?>
有什么特别的关系。如果返回Class
,代码可以很好地编译。这是对您正在做的操作的模拟,并且此测试通过。我认为这对你也是有效的:
package com.sandbox;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.mockito.Mockito.*;
import static junit.framework.Assert.assertEquals;
public class SandboxTest {
@Test
public void testQuestionInput() {
SandboxTest methodParameter = mock(SandboxTest.class);
final Class<?> userClass = String.class;
when(methodParameter.getParameterType()).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
return userClass;
}
});
assertEquals(String.class, methodParameter.getParameterType());
}
public Class<?> getParameterType() {
return null;
}
}
https://stackoverflow.com/questions/16890133
复制相似问题