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
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
public class ProjectDefinitionTest {
@Test
public void shouldSetKey() {
ProjectDefinition def = ProjectDefinition.create();
def.setKey("mykey");
assertThat(def.getKey(), is("mykey"));
}
}
Resources
Documentation
Articles & blog posts