rspec/rules/S5776/java/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
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.
2023-05-25 14:18:12 +02:00

77 lines
2.2 KiB
Plaintext

== Why is this an issue?
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.
----
== 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
Consider using org.junit.Assert.assertThrows before other assertions.
=== Highlighting
"expect"
endif::env-github,rspecator-view[]