我正在尝试测试使用ContextWrapper类的模块。
我尝试使用此代码模拟它:
ContextWrapper contextWrapper = mock(ContextWrapper.class);
File myFile = mock(File.class);
doReturn(mFile).when(contextWrapper).getDir(anyString(), anyInt());
正在测试的方法仍然使用自己的ContextWrapper声明 并返回一个例外
java.lang.RuntimeException: Method getDir in android.content.ContextWrapper not mocked
我已经检查了与此问题相关的其他条目,我发现它可能是由于是一个独家的Android类。
我也试过Mockito v2的
given(contextWrapper.getDir(AppFolders.getFolderPath(), Context.MODE_PRIVATE)).willReturn(mFile);
编辑: 这是我试图测试的模块
public void send(final String id, final ErrorReport errorReport, final MyCallback callback) {
if(null == errorReport || null == errorReport.getType()){
callback.result("Error Report Empty"));
return;
}
try {
processResponse(sendReport(id, errorReport),
callback,
new Executable() {
@Override
public void execute() throws Exception {
callback.result("SUCCESS");
}
},
origin);
} catch (Exception e) {
e.printStackTrace();
}}
和 这是ContextWrapper所在的模块
private MyResponse sendReport(String id, ErrorReport errorReport) throws Exception {
ContextWrapper contextWrapper = new ContextWrapper(context);
AppFolders.setCustomerInfoZipFilename(id);
File logFolder = contextWrapper.getDir(AppFolders.getFolderPath(), Context.MODE_PRIVATE);
File zipFile = new File(logFolder.getAbsolutePath() + AppFolders.getCustomerInfoZipFilename());
String zipBase64 = getBase64String(zipFile);
ErrorReportData errorReportData = new ErrorReportData();
errorReportData.setData(zipBase64);
MyResponse response = myClient.errorReport(errorReportData);
return response;}
这是测试模块
public class Send extends BaseTest{
private static final String URL_METHOD_CALL = "send/";
private File myFile;
private ContextWrapper contextWrapper;
@Test
public void when_send_response_valid_then_callback_success() throws Exception {
ErrorReport errorReport = new ErrorReport();
errorReport.setType(new ErrorType());
contextWrapper = mock(ContextWrapper.class);
myFile = mock(File.class);
whenNew(ContextWrapper.class).withArguments(any(Context.class)).thenReturn(contextWrapper);
doReturn(myFile).when(contextWrapper).getDir(anyString(), anyInt());
MyResponse response = MockClient.getMockClient().submit(mockHost+URL_METHOD_CALL, StatusCode.STATUS_SUCCESS);
doSetToken();
when(client.errorReport(any(ErrorReportData.class), any(ClientImpl.Header.class))).thenReturn(response);
service.send(mockUser, errorReport, new Callback<String>() {
@Override
public void result(Response<String> response) {
assertEquals(StatusCode.STATUS_SUCCESS, response.getStatus());
}
});
}}
答案 0 :(得分:0)
试试这个
File myFile = mock(File.class);
when(contextWrapper.getDir(anyString(), anyInt())).thenReturn(myFile);