
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
82 lines
2.3 KiB
Plaintext
82 lines
2.3 KiB
Plaintext
== Why is this an issue?
|
||
|
||
When testing exception via ``++@Test++`` annotation, having additional assertions inside that test method can be problematic because any code after the raised exception will not be executed. It will prevent you to test the state of the program after the raised exception and, at worst, make you misleadingly think that it is executed.
|
||
|
||
|
||
You should consider moving any assertions into a separate test method where possible, or using https://github.com/junit-team/junit4/wiki/Exception-testing#using-assertthrows-method[org.junit.Assert.assertThrows] instead.
|
||
|
||
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]
|
||
----
|
||
@Test(expected = IndexOutOfBoundsException.class)
|
||
public void testShouldFail() {
|
||
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]
|
||
----
|
||
// This test correctly fails.
|
||
@Test
|
||
public void testToString() {
|
||
Object obj = get();
|
||
Assert.assertThrows(IndexOutOfBoundsException.class, () -> obj.toString());
|
||
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]
|
||
----
|
||
@Test
|
||
public void testShouldFail() {
|
||
Object obj = get();
|
||
try {
|
||
obj.toString();
|
||
Assert.fail("Expected an IndexOutOfBoundsException to be thrown");
|
||
} catch (IndexOutOfBoundsException e) {}
|
||
Assert.assertEquals(0, 1); // Correctly fails.
|
||
}
|
||
----
|
||
|
||
|
||
== Resources
|
||
|
||
* 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)
|
||
|
||
=== Message
|
||
|
||
Move assertions into separate method or use assertThrows or try-catch instead.
|
||
|
||
|
||
=== Highlighting
|
||
|
||
primary: "expected = XXX.class" inside @Test annotation
|
||
|
||
secondary: assertions inside the method
|
||
|
||
|
||
endif::env-github,rspecator-view[]
|