Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Testing a thrown exception with JUnit in Gradle

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading