rspec/rules/S5778/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

87 lines
2.0 KiB
Plaintext

== Why is this an issue?
When verifying that code raises a runtime exception, a good practice is to avoid having multiple method calls inside the tested code, to be explicit about which method call is expected to raise the exception.
It increases the clarity of the test, and avoid incorrect testing when another method is actually raising the exception.
=== Noncompliant code example
[source,java]
----
@Test
public void testToString() {
// Do you expect get() or toString() throwing the exception?
org.junit.Assert.assertThrows(IndexOutOfBoundsException.class, () -> get().toString());
}
@Test
public void testToStringTryCatchIdiom() {
try {
// Do you expect get() or toString() throwing the exception?
get().toString();
Assert.fail("Expected an IndexOutOfBoundsException to be thrown");
} catch (IndexOutOfBoundsException e) {
// Test exception message...
}
}
----
=== Compliant solution
[source,java]
----
@Test
public void testToString() {
Object obj = get();
Assert.assertThrows(IndexOutOfBoundsException.class, () -> obj.toString());
}
@Test
public void testToStringTryCatchIdiom() {
Object obj = get();
try {
obj.toString();
Assert.fail("Expected an IndexOutOfBoundsException to be thrown");
} catch (IndexOutOfBoundsException e) {
// Test exception message...
}
}
----
== 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
Refactor {the body of this try/catch|the code of this assertThrows} to have only one invocation throwing an exception.
=== Highlighting
* Primary: assertThrows/try keyword
* Secondaries: Methods calls
'''
== Comments And Links
(visible only on this page)
=== is related to: S5783
=== on 16 Apr 2020, 10:07:40 Quentin Jaquier wrote:
RSPEC-5783 created to target checked exceptions
endif::env-github,rspecator-view[]