在我的例子中,when(mockobj.method()).thenreturn(value)不返回value,而是返回null。
我在模仿一个被模仿对象的行为并测试它,如下所示。
@Test
void testCallToServer() {
RequestResp request = new RequestResp();
RequestResp response = new RequestResp();
ServerImpl serverImpl = mock(ServerImpl.class);
Mockito.when(factory.getCamelServiceInstance(Mockito.isA(Integer.class))).thenReturn(serverImpl);
Mockito.when(serverImpl.process(Mockito.isA(String.class), Mockito.isA(RequestResp.class), Mockito.isA(Class.class)))
.thenReturn(response);
assertNotNull(common.callToServer(request));
}
实际方法(calltoserver)定义:
public RequestResp callToServer(RequestResp request) {
int SVR_IDENTIFIER = 3;
CamelService serverServiceImpl = factory.getCamelServiceInstance(SVR_IDENTIFIER);
RequestResp response = serverServiceImpl.process("direct:svrRoute", request, RequestResp.class);
return response;
}
服务类中的实际(进程)方法:
public abstract class CamelService {
public <T> T process(String route,Object request, Class<T> responseClass) {
Object response = template.requestBody(route, request, responseClass);
return (T) response;
}
}
类serverimpl:
public class ServerImpl extends CamelService {}
在模拟了上述测试用例中进程的行为之后,在mock-serverimpl上调用这个方法,它仍然给出null响应,因此assertnotnull在测试用例中失败。
我甚至尝试过使用mockito.any()参数匹配器,结果还是一样的。这里怎么了?
为什么以下方法过程模拟不起作用:
Mockito.when(serverImpl.process(Mockito.isA(String.class), Mockito.isA(RequestResp.class), Mockito.isA(Class.class)))
.thenReturn(response);
暂无答案!
目前还没有任何答案,快来回答吧!