-1
我正在爲使用FileInputStream
的方法編寫JUnit
,並且在constructor
中只傳遞文件名。該文件是作爲servlet請求的一部分創建的,並且此文件不存儲在任何位置。在沒有現有文件的情況下使用Mockito/PowerMockito模擬FileInputStream
我想Mock
FileInputStream
使用PowerMockito
,這樣它給了我一個模擬的文件對象。不幸的是我得到FileNotFoundException
這是有效的,但我不知道如何測試這種方法,然後因爲該文件不存在。被測
方法:
public String viewReport() throws Exception {
this.inputStream = new FileInputStream(DOCUSIGN_REPORT_FILE);
try {
boolean returnReport = validateRequest();
if (returnReport) {
intgList = this.generateViewIntegrationReportData(getESignUIConfig());
this.createCSVFile(intgList, new FileWriter(DOCUSIGN_REPORT_FILE));
} else {
failureResponse(msgs, 400);
return null;
}
} catch (Exception e) {
e.printStackTrace();
msgs.add(new Message(ESignatureIntegrationMessageTypeEnum.MESSAGE_TYPE_ERROR,
UiIntegrationKeyConstants.UI_INTEGRATION_ERROR_CODE_500, UiIntegrationKeyConstants.UI_INTEGRATION_ERROR_TEXT_SERVICE_ERROR));
failureResponse(msgs, 500);
return null;
}
return UiIntegrationKeyConstants.REPORT_REPSONSE;
}
的JUnit至今測試。
@Test
public void testViewReport() throws Exception {
Map<String, Object> actionMap = new HashMap<>();
actionMap.put("application", "ESignatureIntegrationAction");
ActionContext.setContext(new ActionContext(actionMap));
FileInputStream inputStream = Mockito.mock(FileInputStream.class);
PowerMockito.whenNew(FileInputStream.class).withAnyArguments().thenReturn(inputStream);
action = new ESignatureIntegrationAction();
action.viewReport();
}
我得到一個exception
當代碼達到new FileInputStream(DOCUSIGN_REPORT_FILE);
感謝您的幫助。
通常的警告:如果你要使用工廠(和依賴注入一起)......那麼你不需要Powermock來模擬一個新的調用。 – GhostCat
你的意思是我應該使用Spring注入FileInputStream? – Jaykumar
如果您的代碼無法從中讀取某些文件,您的測試會測試什麼? –