Skip to content

[java] PMD could enforce non-public methods for Junit5 / Jupiter test methods #3239

@ajeans

Description

@ajeans

Proposed Rule Name: JUnit5TestShouldBePackagePrivate

Proposed Category: Best Practices

Description:
JUnit 5 tests should be package private at the class level and for each method that uses @Test, @RepeatedTest,
@TestFactory, @TestTemplate or @ParameterizedTest.

Contrary to JUnit4 tests that required public visibility to be run by the engine, JUnit5 tests can also be run
if they're package-private. Marking them as such is a good practice to limit their visibility.

Code Sample:

class MyTest { // not public, that's fine
    @Test
    public void testBad() { } // should not have a public modifier
    @Test
    protected void testAlsoBad() { } // should not have a protected modifier
    @Test
    void testGood() { } // package private as expected
}

Possible Properties:

  • There is no necessity for a property yet.

Original feature request

Is your feature request related to a problem? Please describe.

We work with Junit 5 for our tests and PMD does not warn us when declare test methods as public. This is not needed anymore, so we would like PMD to assert that methods are not public nor private.
See https://junit.org/junit5/docs/current/user-guide/#writing-tests-classes-and-methods

Slightly related to #428 which was PMD incorrectly requiring the public modifier, we would like to go further and have PMD require that the modifier should not be public.

Describe the solution you'd like
An additional rule JUnit5TestNoPublicOrPrivateModifier to error out on methods marked as @Test and with a public or private modifier.

Describe alternatives you've considered
Adding Sonar to our CI, which reports this as an issue

Additional context
Some other ideas for Junit 5 are in #2616

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:new-ruleProposal to add a new built-in rulean:enhancementAn improvement on existing features / rules

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions