首页 > 解决方案 > 在使用 FileInputStream 对 main 方法使用 Junit 测试时使用 assertThrows

问题描述

我目前正在尝试将 JUnit 测试用于我的主谋游戏的主要方法。我的输入文件包含一个输入长度非法的输入,我希望我的主要方法会在某处抛出异常。如何检查在我的 main 方法执行期间是否引发了异常?我一直在尝试使用以下代码来解决这个问题:

@Test
void testPlayErrors2() throws FileNotFoundException {
    String[] args= null;
    final InputStream original=System.in; 
    final InputStream fileIn= new FileInputStream(
        new File("playTest.txt"));
    System.setIn(fileIn);
    assertThrows(
               MastermindIllegalLengthException.class,
               () -> (Mastermind.main(args)),
               "Expected Mastermind.main() to throw MastermindIllegalLengthException, but it didn't"
        );
    
    System.setIn(original);
}

我在使用 assertthrows 时遇到编译错误。我确切地知道我的文本文件中应该抛出异常的那一行,所以我也可以跟踪输入流,就像一次给它一行,然后在我期望的地方捕获异常但是我不知道该怎么做。

标签: javajunitassertfileinputstream

解决方案


您必须从 Mastermind.main(args) 中删除括号:

assertThrows(
  MastermindIllegalLengthException.class,
  () -> Mastermind.main(args),
  "Expected Mastermind.main() to throw MastermindIllegalLengthException, but it didn't"
);

我还将删除该消息并使用 JUnit 的标准错误消息:

assertThrows(
  MastermindIllegalLengthException.class,
  () -> Mastermind.main(args)
);

推荐阅读