java - 如何为此 "FileNotFoundException"编写Junit测试

标签 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");
            }
        }

    }

最佳答案

实际上,您打算做的是测试 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/

相关文章:

java - MyBatis 没有找到适合 jdbc 的驱动 :sqlserver

java - 光标问题

wcf - 在 WCF 中 - 在 "Faulted"事件中 - 如何获取异常详细信息?

c# - 无法枚举 C# 中的 F# 列表列表

eclipse - JUnit 无法在 Eclipse 中找到测试

java - java如何选择.JAR库版本

java - 确保每次调用 B(抽象实现的方法)后调用方法 A?

java - 多捕获异常处理程序中的顺序

java - Maven 是否使编写测试套件的需要变得过时了?

java - Spring的测试注解@Sql如何表现得像@BeforeClass?