JUnit5 test methods should generally have package visibility. To fix this issue, remove the public or protected
visibility modifiers from the test methods.
JUnit5 is more tolerant regarding the visibility of test classes and methods than JUnit4, which required everything to be public. Test
classes and methods can have any visibility except private. It is however recommended to use the default package visibility to improve
readability.
— JUnit5 User GuideTest classes, test methods, and lifecycle methods are not required to be
public, but they must not beprivate.It is generally recommended to omit the public modifier for test classes, test methods, and lifecycle methods unless there is a technical reason for doing so – for example, when a test class is extended by a test class in another package. Another technical reason for making classes and methods public is to simplify testing on the module path when using the Java Module System.
The code will be non-conventional and readability can be slightly affected.
This rule does not raise an issue when the visibility is set to private, because private test methods are systematically
ignored by JUnit5, without a proper warning. In this case, there is also an impact on reliability and so it is handled by the rule
{rule:java:S5810}.
Note that this rule does not flag the visibility modifier of the test class itself, because there can be legitimate reasons to keep a test class public — for example, when it is referenced in a test suite or extended by a test class in another package.
Remove the public or protected keywords from the test methods.
import org.junit.jupiter.api.Test;
class MyClassTest { // Noncompliant - test methods have redundant visibility modifiers
@Test
public void test() { // secondary location
// ...
}
}
import org.junit.jupiter.api.Test;
class MyClassTest {
@Test
void test() {
// ...
}
}