Cor*_*han 30 java junit mockito
我正在尝试编写单元测试,为此我正在为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的一个问题,还是我做错了什么?
小智 65
另外,稍微简洁一点的方法是使用do语法而不是when.
doReturn(User.class).when(methodParameter).getParameterType();
Run Code Online (Sandbox Code Playgroud)
fgb*_*fgb 27
Class<?> userClass = User.class;
OngoingStubbing<Class<?>> ongoingStubbing = Mockito.when(methodParameter.getParameterType());
ongoingStubbing.thenReturn(userClass);
Run Code Online (Sandbox Code Playgroud)
在OngoingStubbing<Class<?>>返回的Mockito.when是不一样的类型ongoingStubbing,因为每一个"?" 通配符可以绑定到不同的类型.
要使类型匹配,您需要显式指定类型参数:
Class<?> userClass = User.class;
Mockito.<Class<?>>when(methodParameter.getParameterType()).thenReturn(userClass);
Run Code Online (Sandbox Code Playgroud)
Dan*_*lan 12
我不确定你为什么会收到这个错误.它必须与返回有一些特殊的关系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;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以简单地从课堂中删除))
Class userClass = User.class;
when(methodParameter.getParameterType()).thenReturn(userClass);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24782 次 |
| 最近记录: |