0
我有try-catch塊的一段代碼:Junit的與異常
public static void writeExcelToFile(String outFileName, HSSFWorkbook workBook) throws IOException{
File file = null;
FileOutputStream fileOutputStream = null;
try {
file = getFileByFileName(outFileName);
File parent = file.getParentFile();
Path filePath = parent.toPath();
if (Files.notExists(filePath) && !parent.mkdirs()) {
throw new IOException("Couldn't create dir: " + parent);
}
fileOutputStream = new FileOutputStream(file);
workBook.write(fileOutputStream);
} catch (FileNotFoundException fileNotFoundException) {
LOGGER.error("File path is invalid, file not found ", fileNotFoundException);
throw fileNotFoundException;
} catch (IOException ioException) {
LOGGER.error("Exception occured while reading writing file ", ioException);
throw ioException;
} catch (Exception exception) {
LOGGER.error("Exception occured ", exception);
throw exception;
} finally {
if (fileOutputStream != null) {
fileOutputStream.close();
}
}
file.setWritable(true);
}
我寫了下面的JUnit catch塊:
//#1: FileNotFoundException
@Test(expected = java.io.FileNotFoundException.class)
public void testWriteExcelToFileException() throws IOException {
PowerMockito.mockStatic(KnewtonCIExcelWriter.class);
PowerMockito.doThrow(new java.io.FileNotFoundException()).when(KnewtonCIExcelWriter.class);
KnewtonCIExcelWriter.writeExcelToFile(anyString(), anyObject());
}
//#2: IOException
@Test(expected = IOException.class)
public void testWriteExcelIOException() throws IOException {
PowerMockito.mockStatic(KnewtonCIExcelWriter.class);
PowerMockito.doThrow(new IOException()).when(KnewtonCIExcelWriter.class);
KnewtonCIExcelWriter.writeExcelToFile(anyString(), anyObject());
}
//#3: Exception
@Test(expected = Exception.class)
public void testWriteExcelException() throws IOException {
PowerMockito.mockStatic(KnewtonCIExcelWriter.class);
PowerMockito.doThrow(new Exception()).when(KnewtonCIExcelWriter.class);
KnewtonCIExcelWriter.writeExcelToFile(anyString(), anyObject());
}
然而,只有最後,# 3 Junit通行證。 #1和#2給出java.lang.AssertionError:期望的異常:java.io.FileNotFoundException和java.lang.AssertionError:預期的異常:java.io.IOEXception。在doThrow
Question: 1) How to get the #1 and #2 JUnit passing? 2) Am I catching the correct exceptions?
請仔細閱讀powermock文檔,'PowerMockito.doThrow(新的異常())時(KnewtonCIExcelWriter.class);'這是缺少函數名 – 2017-02-13 15:55:56
注意:不要捕獲,記錄和重新拋出異常。記錄它們或重新拋出它們;不要這樣做。 –