rspec/rules/S5776/java/rule.adoc

77 lines
2.2 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
@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
2021-04-28 16:49:39 +02:00
* For JUnit >= 4.13, use https://github.com/junit-team/junit4/wiki/Exception-testing#using-assertthrows-method[org.junit.Assert.assertThrows]:
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
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]:
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
try {
get();
Assert.fail("Expected an IndexOutOfBoundsException to be thrown");
} catch (IndexOutOfBoundsException e) {}
Assert.assertEquals(0, 1); // Correctly fails.
----
== Resources
2021-04-28 16:49:39 +02:00
* 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[]