【发布时间】:2017-07-01 16:20:19
【问题描述】:
我有一段带有 try-catch 块的代码:
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);
}
我为 catch 块编写了以下 Junit:
//#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: Expected exception: java.io.FileNotFoundException 和 java.lang.AssertionError: Expected exception: java.io.IOEXception。
问题:1)如何让#1 和#2 JUnit 通过? 2)我赶上 正确的异常?
【问题讨论】:
-
请阅读 powermock 文档,
PowerMockito.doThrow(new Exception()).when(KnewtonCIExcelWriter.class);缺少函数名 -
注意:不要捕获、记录和重新抛出异常。记录它们或重新扔掉它们;不要两者都做。
标签: java unit-testing junit junit4 junit-runner