我需要为MyClass
类编写测试。
public class MyClass {
public Result<Data> get() {
return Request
.buildRequest(session, Data.class, new DefaultErrorHandler())
.executeAndConvert();
}
}
我的请求类
public class Request<Type> implements RequestBuilder<Type> {
public static <T> Request<T> buildRequest(String session, Class<T> responseClass) {
return buildRequest(session, responseClass, null);
}
public static <T> Request<T> buildRequest(String session, Class<T> responseClass, ErrorHandler errorHandler) {
Request<T> request = new Request<T>(session, responseClass);
// some logic
return request;
}
@Override
public Result<Type> executeAndConvert() {
Invocation.Builder req = buildRequest();
return executeRequest(req);
}
// some other code
}
这是我的测试代码
PowerMockito.mockStatic(Request.class);
PowerMockito.when(Request.buildRequest(sessionMock, Data.class)).thenReturn(requestMock);
myClass.get(); // which is return a Request object
我想禁用Request构造函数调用,因为我在内部触发时会获得NPE。实际上我不需要在构造函数或方法链中调用所有方法。我只需要返回一个模拟的结果。
答案 0 :(得分:0)
PowerMockito.when(Request.buildRequest(sessionMock, Data.class)).thenReturn(requestMock);
与您呼叫的呼叫不匹配:
Request.buildRequest(session, Data.class, new DefaultErrorHandler())
您还应该为ErrorHandler添加匹配器。如果没有设置任何内容,则会返回null
,正如您所说。