91 lines
2.6 KiB
Plaintext
91 lines
2.6 KiB
Plaintext
== Why is this an issue?
|
|
|
|
JUnit rules are predefined classes that extend the behavior of JUnit tests, allowing to add new functionalities,
|
|
such as managing resources, modifying test behavior, and handling exceptions.
|
|
|
|
Unused JUnit rules can lead to confusion when reading the test code, making tests harder to understand and maintain.
|
|
Having unused rules can also slow down the test suite, as JUnit has to process the rules even though they are not being used.
|
|
Some `TestRule` classes have the desired effect without being directly referenced by a test, while others do not.
|
|
There's no reason to leave them cluttering the file if they're not in use.
|
|
|
|
The rule raises an issue when in a `Test` class, there is no method referencing a declared `TestRule` of the following types:
|
|
|
|
* `TemporaryFolder` and `TestName` in JUnit
|
|
* `TempDir` and `TestInfo` in JUnit 5
|
|
|
|
== How to fix it
|
|
|
|
Remove the unused `TestRule` field that is expected to be referenced inside a test method.
|
|
|
|
=== Code examples
|
|
==== Noncompliant code example
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
public class ProjectDefinitionTest {
|
|
|
|
@Rule
|
|
public TemporaryFolder temp = new TemporaryFolder(); // Noncompliant
|
|
|
|
@Test
|
|
public void shouldSetKey() {
|
|
ProjectDefinition def = ProjectDefinition.create();
|
|
def.setKey("mykey");
|
|
assertThat(def.getKey(), is("mykey"));
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
public class ProjectDefinitionTest {
|
|
|
|
@Test
|
|
public void shouldSetKey() {
|
|
ProjectDefinition def = ProjectDefinition.create();
|
|
def.setKey("mykey");
|
|
assertThat(def.getKey(), is("mykey"));
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://junit.org/junit4/javadoc/4.12/org/junit/Rule.html[Junit API - Rule]
|
|
* https://github.com/junit-team/junit4/wiki/Rules[Junit - Rules]
|
|
|
|
=== Articles & blog posts
|
|
|
|
* https://www.baeldung.com/junit-4-rules[Junit 4 Rules]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Remove this unused "TestRule".
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 12 May 2015, 14:25:37 Ann Campbell wrote:
|
|
\[~david.gageot] this may not be as broad as you wanted...?
|
|
|
|
|
|
Also, I'm not quite sure about the impact of the @Rule annotation, so I didn't mention it in the description but left it in the code sample you provided. What happens if the annotation is missing?
|
|
|
|
=== on 12 May 2015, 14:54:12 David Gageot wrote:
|
|
If the annotation is missing, it will not do anything either. So this is really dead code
|
|
|
|
=== on 12 May 2015, 14:54:16 David Gageot wrote:
|
|
lgtm
|
|
|
|
endif::env-github,rspecator-view[]
|