Try catch in a JUnit test

Since Exception is a checked exception, you either:

  • Have to catch the exception in a try...catch statement, or
  • Declare the exception to be thrown in the method itself.

What you have up there works fine, but my personal preference is to declare the exception to be thrown. This way, if an exception I’m not expecting is thrown during the run of the test, the test will fail.

@Test
public void someTest() throws Exception {
    // dodgy code here
}

If we need to see if a specific exception is thrown, then you have the option of using @Rule or adding the value to the @Test annotation directly.

@Test(expected = FileNotFoundException.class)
public void someTest() throws Exception {
    // dodgy code here
}

In JUnit 5, you can leverage Assertions.assertThrows to accomplish the same thing. I’m less familiar with this overall since it’s not yet GA at the time of editing, but it appears to accept an Executable coming from JUnit 5.

@Test
public void someTest() {
    assertThrows(FileNotFoundException.class, () ->
         { dodgyService.breakableMethod() };
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)