如何为此“ FileNotFoundException”编写Junit测试

时间:2019-05-23 03:54:56

标签: java exception junit

如何为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");
            }
        }

    }

2 个答案:

答案 0 :(得分:4)

实际上,您打算做的是测试JVM本身,以查看在某些情况下是否引发了适当的异常。有人认为,它不再是单元测试了,您需要假设外部的东西,JMV方面就可以正常工作,不需要进行测试。

您的方法readList()极不可测试。您想编写一个文件存在性测试,但是要在该方法内创建一个文件对象而不是注入它。您想查看是否引发了异常,但是您将其捕获在该方法中。

我们将其外部化:

public void readList(File inputFile) throws FileNotFoundException {
  //... do your code logic here ...
}

然后您可以在单元测试中使用称为@Rule的JUnit的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);
  }
}

答案 1 :(得分:0)

一旦FileNotFoundException找不到readList()文件,就可以期待numbers.txt。 另外,您正在处理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;
}