I use JUnit 5 inside of a Gradle project. I am trying to test this main function, in package 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);
}
}
Specifically, the try-catch block at the bottom. Here is the test I have written:
@Test
public void testMissingFile() {
String[] args = { "bad_file" };
FileNotFoundException thrown = assertThrows(
FileNotFoundException.class,
() -> P1.main(args));
assertTrue(thrown.getMessage().contains("File not found:"));
}
Unfortunately, this test fails, with this output from gradle test --info
:
TestP1 > testMissingFile() STANDARD_OUT
File not found: bad_file (No such file or directory)
I am trying to catch this error and test that it is thrown, but instead it breaks the test. I was expecting the test to pass the assertions as they check for a FileNotFoundException and assert the contents of the error message.
You are catching the exception in your code and printing the error message and that's exactly the result of the test, the output of System.out.println("File not found: + e.getMessage());
Your code is handling the exception, so the exception is not bubble up to the test.
If you want to test that it throws an exception, you should remove the try/catch
block or throw another exception inside the catch
block.