rspec/rules/S5778/java/rule.adoc

76 lines
1.7 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
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
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
----
@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
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
----
@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
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)
include::message.adoc[]
include::highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]