java - 在使用 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 时遇到编译错误。我确切地知道我的文本文件中应该抛出异常的那一行,所以我也可以跟踪输入流,就像一次给它一行,然后在我期望的地方捕获异常但是我不知道该怎么做。
解决方案
您必须从 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)
);
推荐阅读
- xslt - 如果缺少子节点,则插入配置
- c# - 队列中接收到消息时,是否可以使用 azure 函数从 IBM MQ 接收消息
- c# - 使用 c# 在 Azure DevOps (VSTS) 中创建带有子节点的迭代
- c# - C# 将字符串转换为 JSON
- python - 如何使用mysql在python中修复“InterfaceError:没有要获取的结果集”
- apache-spark - Spark结构化流窗口问题
- ios - IOS swift 4展开和折叠表格视图不起作用并导致崩溃
- google-app-engine - 在谷歌云上部署应用程序期间出现 nltk 问题
- python - 在很长的时间间隔内积分高斯
- openshift-origin - `oc cluster up` 在初始启动期间失败