It is possible to easily catch the exception without any try catch
block.
public class ListTest {
private final List<Object> list = new ArrayList<>();
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
list.get(0);
}
}
The example above should suffice for simpler cases, when you don't want/need to check the message carried by the thrown exception.
If you want to check information about exception you may want to use try/catch block:
@Test
public void testIndexOutOfBoundsException() {
try {
list.get(0);
Assert.fail("Should throw IndexOutOfBoundException");
} catch (IndexOutOfBoundsException ex) {
Assert.assertEquals("Index: 0, Size: 0", ex.getMessage());
}
}
For this example you have to be aware to always add Assert.fail()
to ensure that test will be failed when no Exception is thrown.
For more elaborated cases, JUnit has the ExpectedException
@Rule
, which can test this information too and is used as follows:
public class SimpleExpectedExceptionTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void throwsNothing() {
// no exception expected, none thrown: passes.
}
@Test
public void throwsExceptionWithSpecificType() {
expectedException.expect(NullPointerException.class);
throw new NullPointerException();
}
@Test
public void throwsExceptionWithSpecificTypeAndMessage() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Wanted a donut.");
throw new IllegalArgumentException("Wanted a donut.");
}
}
To achieve the same in JUnit 5, you use a completely new mechanism:
public class Calculator {
public double divide(double a, double b) {
if (b == 0.0) {
throw new IllegalArgumentException("Divider must not be 0");
}
return a/b;
}
}
public class CalculatorTest {
@Test
void triangularMinus5() { // The test method does not have to be public in JUnit5
Calculator calc = new Calculator();
IllegalArgumentException thrown = assertThrows(
IllegalArgumentException.class,
() -> calculator.divide(42.0, 0.0));
// If the exception has not been thrown, the above test has failed.
// And now you may further inspect the returned exception...
// ...e.g. like this:
assertEquals("Divider must not be 0", thrown.getMessage());
}