繁体   English   中英

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

[英]Using assertThrows while using Junit test for main method using 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);
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM