If one does not expect an Exception
to be thrown, there is no added benefit in adding a try-catch
block to the code. Even worse, only adding a try-catch
block will lead to the test passing. To make the test fail, one would have to add a call to fail()
to make the test actually fail. This is a possible source for error (if one forgets to call fail()
).
For completeness sake, I will talk shortly about how to verify that a certain Exception
has been thrown. There are three approaches that come to my mind.
In the first attempt, one could use try-catch
, but with an added fail()
in the try
-block, just after the calls that should throw the expected Exception
. In the catch
-block, one would then catch the expected Exception
. All other Exception
s would be re-thrown and thus the test would fail. This has the same downsides as its sibling mentioned above.
Second, there is the JUnit4 way by annotating the test itself with @Test(expected = ExpectedException.class)
. This seems neat at first, but breaks the Given-When-Then structure of tests, often leading to tests looking like this:
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void test() {
// GIVEN
final int[] array = new int[10];
// WHEN
final int value = array[10];
// THEN: an ArrayIndexOutOfBoundsException should be thrown
}
which is okay-ish.
Lastly, there is the JUnit5 way by wrapping the actual call into a call of assertThrows(...)
:
@Test(expected = ArrayIndexOutOfBoundsException.class)
void test() {
// GIVEN
final int[] array = new int[10];
// WHEN
final Exception e = assertThrows(ArrayIndexOutOfBoundsException.class,
() -> {
int value = array[10];
}
);
// THEN
assertTrue(e.getMessage().contains("10"));
}
While this still does not properly separates the WHEN
from the THEN
(I think this is not possible in Java), it gives the added benefit to allow checking specific parts of the Exception
, e.g. the message1.
I would suggest this article over at Baelung as a further read.
1This is also possible in JUnit4, but is either done through an explicit try-catch
block or through a very cumbersome mechanism that definitively breaks the Given-When-Then structure. For more information, please check the article over at Baelung mentioned above.