如何为 FileNotFoundException 编写 Junit 测试,我是否需要在测试中执行某些操作以使我的“numbers.txt”文件不被看到?
public void readList() {
Scanner scanner = null;
try {
scanner = new Scanner(new File("numbers.txt"));
while (scanner.hasNextInt()) {
final int i = scanner.nextInt();
ListOfNumbers.LOGGER.info("{}", i);
}
} catch (final FileNotFoundException e) {
ListOfNumbers.LOGGER.info("{}","FileNotFoundException: " + e.getMessage());
} finally {
if (scanner != null) {
ListOfNumbers.LOGGER.info("{}","Closing PrintReader");
scanner.close();
} else {
ListOfNumbers.LOGGER.info("{}","PrintReader not open");
}
}
}
最佳答案
实际上,您打算做的是测试 JVM 本身,看看在某些条件下是否抛出正确的异常。有些人认为,这不再是单元测试,您需要假设外部 JMV 方面的内容可以正常工作,不需要进行测试。
你的方法readList()
是高度不可测试的。您想要编写文件存在性的测试,但您在该方法内创建一个文件对象而不是注入(inject)它。您想查看是否抛出异常,但您在该方法中捕获了它。
让我们具体化一下:
public void readList(File inputFile) throws FileNotFoundException {
//... do your code logic here ...
}
然后,您可以在单元测试中使用名为 ExpectedException
的 JUnit 的 @Rule
:
@RunWith(MockitoJUnitRunner.class)
public class ReaderTest {
@Rule
public ExpectedException exception = ExpectedException.none(); // has to be public
private YourReader subject = new YourReader();
@Test(expect = FileNotFoundException.class)
public void shouldThrowFNFException() {
// given
File nonExistingFile = new File("blabla.txt");
// when
subject.readList(nonExistingFile);
}
// ... OR ...
@Test
public void shouldThrowFNFExceptionWithProperMessage() {
// given
File nonExistingFile = new File("blabla.txt");
exception.expect(FileNotFoundException.class);
exception.exceptionMessage("your message here");
// when
subject.readList(nonExistingFile);
}
}
关于java - 如何为此 "FileNotFoundException"编写Junit测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56267871/