我在Gradle项目中使用JUnit 5。我正试图在P1包中测试此主要功能:
public static void main(String[] args) {
// Gets command line arguments
String fileName = null;
if (args != null && args.length == 1) {
fileName = args[0];
} else {
throw new IllegalArgumentException("Please specify name of file.");
}
// Initializes file and scanner from provided path
File file = new File(fileName);
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
System.exit(1);
}
}
特别是底部的try-catch块。这是我写的测试:
@Test
public void testMissingFile() {
String[] args = { "bad_file" };
FileNotFoundException thrown = assertThrows(
FileNotFoundException.class,
() -> P1.main(args));
assertTrue(thrown.getMessage().contains("File not found:"));
}
不幸的是,此测试失败,输出来自
gradle test --info
:
TestP1 > testMissingFile() STANDARD_OUT
File not found: bad_file (No such file or directory)
我试图捕捉这个错误并测试它是否被抛出,但它破坏了测试。我希望测试在检查FileNotFoundException并断言错误消息的内容时通过断言。