[英]How to write Junit test for this “FileNotFoundException”
如何为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()
极不可测试。 您想编写一个文件存在性测试,但是要在该方法内创建一个文件对象而不是注入它。 您想查看是否抛出了异常,但是您将其捕获在该方法中。
让我们将其外部化:
public void readList(File inputFile) throws FileNotFoundException {
//... do your code logic here ...
}
然后,可以在单元测试中使用JUnit的@Rule
称为ExpectedException
:
@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);
}
}
一旦您的readList()
无法找到numbers.txt
文件,就可以期待FileNotFoundException
。 另外,您正在处理FileNotFoundException
因此需要再次将其throw
catch块中。
尝试像:
@Test(expected = java.io.FileNotFoundException.class)
public void testReadListForFileNotFoundException(){
// call your method readList
}
扔它,以便您的测试用例可以预期。
catch (final FileNotFoundException e) {
ListOfNumbers.LOGGER.info("{}","FileNotFoundException: " + e.getMessage());
throw e;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.