对使用 FileInputStream

问题描述

我目前正在尝试将 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);
}

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

解决方法

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