在对使用 FileInputStream 的主要方法使用 Junit 测试时使用 assertThrows

Using assertThrows while using Junit test for main method using FileInputStream

我目前正在尝试将 JUnit 测试用于 mastermind 游戏的主要方法。我的输入文件包含一个输入长度非法的输入,我希望我的主要方法在某处抛出异常。如何检查在执行 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 时遇到编译错误。我确切地知道我的文本文件中应该抛出异常的行,所以我也可以跟踪输入流,就像一次给它一行,然后在我期望的地方捕获异常但是我不知道该怎么做。

您必须从 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)
);