69 lines
2.1 KiB
Plaintext
69 lines
2.1 KiB
Plaintext
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 https://github.com/junit-team/junit4/wiki/Exception-testing#using-assertthrows-method[org.junit.Assert.assertThrows] instead, it's available since JUnit 4.13 and it allows additional subsequent assertions.
|
|
|
|
Alternatively, you could use https://github.com/junit-team/junit4/wiki/Exception-testing#trycatch-idiom[try-catch idiom] for JUnit version < 4.13 or if your project does not support lambdas.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
[source,java]
|
|
----
|
|
@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
|
|
|
|
* For JUnit >= 4.13, use https://github.com/junit-team/junit4/wiki/Exception-testing#using-assertthrows-method[org.junit.Assert.assertThrows]:
|
|
|
|
[source,java]
|
|
----
|
|
Assert.assertThrows(IndexOutOfBoundsException.class, () -> get());
|
|
// This test correctly fails.
|
|
Assert.assertEquals(0, 1);
|
|
----
|
|
|
|
* For JUnit < 4.13, use the https://github.com/junit-team/junit4/wiki/Exception-testing#trycatch-idiom[try-catch idiom]:
|
|
|
|
[source,java]
|
|
----
|
|
try {
|
|
get();
|
|
Assert.fail("Expected an IndexOutOfBoundsException to be thrown");
|
|
} catch (IndexOutOfBoundsException e) {}
|
|
Assert.assertEquals(0, 1); // Correctly fails.
|
|
----
|
|
|
|
|
|
== See
|
|
|
|
* https://github.com/junit-team/junit4/wiki/Exception-testing[JUnit exception testing documentation]
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
include::highlighting.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|