When testing exception via org.junit.rules.ExpectedException
any code after the raised exception will not be executed, so adding
subsequent assertions is wrong and misleading. This rule raises an issue when an assertion is done after the "expect(…)" invocation, only the code
throwing the expected exception should be after "expect(…)".
You should consider using org.junit.Assert.assertThrows instead, it’s available
since JUnit 4.13 and it allows additional subsequent assertions.
Alternatively, you could use try-catch idiom for JUnit
version < 4.13 or if your project does not support lambdas.
Noncompliant code example
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void test() throws IndexOutOfBoundsException {
thrown.expect(IndexOutOfBoundsException.class); // Noncompliant
Object o = get();
// This test pass since execution will never get past this line.
Assert.assertEquals(0, 1);
}
private Object get() {
throw new IndexOutOfBoundsException();
}
Compliant solution
Assert.assertThrows(IndexOutOfBoundsException.class, () -> get());
// This test correctly fails.
Assert.assertEquals(0, 1);
try {
get();
Assert.fail("Expected an IndexOutOfBoundsException to be thrown");
} catch (IndexOutOfBoundsException e) {}
Assert.assertEquals(0, 1); // Correctly fails.