GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [java] PMD could enforce non-public methods for Junit5 / Jupiter test methods · Issue #3239 · pmd/pmd

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

New issue
Copy link
New issue
Copy link
Closed
#3247
Closed
[java] PMD could enforce non-public methods for Junit5 / Jupiter test methods#3239
#3247
Copy link
Labels
a:new-ruleProposal to add a new built-in rulean:enhancementAn improvement on existing features / rules
Milestone
6.35.0

Description

@ajeans
ajeans
opened on Apr 29, 2021
Issue body actions

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

Activity

  1. ajeans
    added
    an:enhancementAn improvement on existing features / rules
    on Apr 29, 2021
  2. adangel
    added
    a:new-ruleProposal to add a new built-in rule
    on Apr 29, 2021
  3. ajeans commented on Apr 29, 2021

    @ajeans
    ajeans
    on Apr 29, 2021
    ContributorAuthor
    More actions

    Looking into this locally, it seems to be doable with another XPath rule like

    //ClassOrInterfaceDeclaration[
           matches(@SimpleName, $testClassPattern)]
    
        /ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration
            [MethodDeclaration[@Public=true() or @Private=true()]]
            [Annotation//Name[
                pmd-java:typeIs('org.junit.jupiter.api.Test') or pmd-java:typeIs('org.junit.jupiter.api.RepeatedTest')
                or pmd-java:typeIs('org.junit.jupiter.api.TestFactory') or pmd-java:typeIs('org.junit.jupiter.api.TestTemplate')
                or pmd-java:typeIs('org.junit.jupiter.params.ParameterizedTest')
            ]]
    
  4. ajeans commented on Apr 29, 2021

    @ajeans
    ajeans
    on Apr 29, 2021
    ContributorAuthor
    More actions

    I can do a MR if there is interest...

  5. adangel commented on Apr 30, 2021

    @adangel
    adangel
    on Apr 30, 2021
    Member
    More actions

    Thanks for the suggestion!

    I'm currently thinking about how this new rule would fit into the existing rules we have for (J)Unit testing. Some rules have "JUnit4" in their name, but actually consider Junit 3-5 (e.g. JUnit4TestShouldUseTestAnnotation), which means, we probably should rename the rule at some point.

    This new rule would do two things:

    • It flags test methods, that are private: This is an error - since it won't work.
    • It flags test methods, that are public: This is a matter of taste. The test still works, but this is not required anymore with JUnit5. But it is also not a must. PMD could declare it as a "best practice" though.

    Looking at the sonar rules, I find these:

    • https://rules.sonarsource.com/java/tag/tests/RSPEC-5810 -> this is the error case
    • https://rules.sonarsource.com/java/tag/tests/RSPEC-5786 -> which is exactly the second case (although a bit extended, because it also flags "protected" and only allows package-private). I was interested for the rationale, but it just says "... to use the default package visibility, which improves readability of code".

    If we would do a single rule, I could imagine a name like "CorrectTestMethodDeclaration" - but since it finds an error and a best-practice-violation, it is difficult to find a single category...

    So maybe we should really have two rules:

    • JUnit5TestNoPrivateModifier in category "error prone"
    • JUnit5TestShouldBePackagePrivate in category "best practice" or "code style"

    I'm still unsure about the names containing "JUnit5" explicitly, but maybe these rules really only apply to JUnit5 and no other test frameworks. The first rule "JUnit5TestNoPrivateModifier" would probably also apply to JUnit4, so the name could also be "JUnitTestWrongModifier" (for JUnit4, private, protected and no modifier would be flagged, for JUnit5 only private modifier would be flagged). The second rule would only apply for JUnit5.

    Reacted by Arnaud Jeansen
  6. ajeans commented on Apr 30, 2021

    @ajeans
    ajeans
    on Apr 30, 2021
    ContributorAuthor
    More actions
    JUnit5TestNoPrivateModifier in category "error prone"
    JUnit5TestShouldBePackagePrivate in category "best practice" or "code style"
    

    Sounds good

    Thinking further about jupiter support, I noticed that I didn't mention public jupiter classes, which are also not recommended and are covered by https://rules.sonarsource.com/java/RSPEC-5786 (which covers both public methods and public classes).

    I wrote a separate xpath rule for the public class case (adding non abstract) and ended up with

    //ClassOrInterfaceDeclaration[
           matches(@SimpleName, $testClassPattern) and
           @Abstract=false() and
           @Public=true()
           ]
    
        /ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration
            [MethodDeclaration]
            [Annotation//Name[
                pmd-java:typeIs('org.junit.jupiter.api.Test') or pmd-java:typeIs('org.junit.jupiter.api.RepeatedTest')
                or pmd-java:typeIs('org.junit.jupiter.api.TestFactory') or pmd-java:typeIs('org.junit.jupiter.api.TestTemplate')
                or pmd-java:typeIs('org.junit.jupiter.params.ParameterizedTest')
            ]]
    ]]>
    

    However I don't see how to implement the two ideas (public class and public method) into a single XPath rule for JUnit5TestShouldBePackagePrivate

    So JUnit5TestMethodShouldBePackagePrivate and JUnit5TestClassShouldBePackagePrivate ?

  7. oowekyala commented on May 1, 2021

    @oowekyala
    oowekyala
    on May 1, 2021
    Member
    More actions

    However I don't see how to implement the two ideas (public class and public method) into a single XPath rule for JUnit5TestShouldBePackagePrivate

    You can join the two xpath expressions with the union operator: |

  8. ajeans commented on May 4, 2021

    @ajeans
    ajeans
    on May 4, 2021
    ContributorAuthor
    More actions

    ⬆️ I pushed a simple MR for JUnit5TestShouldBePackagePrivate, I am interested in seeing this upstream :)

  9. adangel
    added this to the 6.35.0 milestone on May 21, 2021
  10. oowekyala
    closed this as completedin #3247on May 25, 2021
  11. adangel
    added a commit that references this issue on May 25, 2021

    [doc] Update release notes (#3247, #3239)

    993ae82
  12. MPoorter commented on Sep 13, 2021

    @MPoorter
    MPoorter
    on Sep 13, 2021
    More actions

    @ajeans @adangel Why is protected considered wrong here? We have certain tests defined in abstract classes that get overridden in subclasses that are not in the same package (because the default implementation of the test method doesn't work for the subclass). This rule now causes issues, can we allow for protected modifiers on the test methods?

  13. ajeans commented on Sep 14, 2021

    @ajeans
    ajeans
    on Sep 14, 2021
    ContributorAuthor
    More actions

    Hello @MPoorter

    Can you provide a short example that shows the problem?

    I understand that you are inheriting protected methods annotated with @org.junit.jupiter.api.Test from the parent and running them directly. Is that correct?

    What happens if you convert the parent class to an interface with default methods (see https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-interfaces-and-default-methods)?

    Thanks.

    Reacted by Z1K
  14. MPoorter commented on Sep 16, 2021

    @MPoorter
    MPoorter
    on Sep 16, 2021
    More actions

    Hi @ajeans

    Our abstract class looks like this

    public abstract class AbstractFeignClientTest {
    
        @Test
        void testHystrixEmptyResponse() {
            doFaultTest(EMPTY_RESPONSE);
        }
    
        @Test
        void testHystrixConnectionReset() {
            doFaultTest(CONNECTION_RESET_BY_PEER);
        }
    
        @Test
        @SuppressWarnings("PMD.JUnit5TestShouldBePackagePrivate")
        protected void testHystrixMalformedResponse() {
            doFaultTest(MALFORMED_RESPONSE_CHUNK);
        }
    
        @Test
        void testHystrixRandomData() {
            doFaultTest(RANDOM_DATA_THEN_CLOSE);
        }
    
        protected abstract void executeFault(Fault fault);
    
        protected abstract ResponseDefinitionBuilder success();
    
        protected abstract MappingBuilder getRequest();
    
        private void doFaultTest(final Fault fault) {
            stubFor(getRequest().willReturn(success().withFault(fault)));
            executeFault(fault);
        }
    }
    

    As you can see, most of the tests defined in the abstract class are package private and don't cause any issues. However, occasionally we cannot rely on the default implementation for the testHystrixMalformedResponse and we override it in a subclass that is not in the same package. Therefore, we need to specify it's protected so that subclasses have access to this method.

    I'm not sure whether the interface solution would work for us, I would need to look into it further but we do have Spring bean injection in our abstract class (not shown here), which makes me wonder whether that would work for us.

    I also wonder whether the interface is the correct solution, as I understand that any default methods in an interface are by nature public. If this rule is set up to prevent public methods for Junit5 tests, then default test methods in interfaces should break that rule, even if there is no access modifier specified.

    The way I understood the benefit of this rule is that with Junit5, we no longer need to say that test methods are public (unlike in Junit4). However, I don't understand why protected also needs to be taken up in this rule?

    Happy to hear your thoughts on this,
    Thanks,
    Matt

  15. ajeans commented on Sep 22, 2021

    @ajeans
    ajeans
    on Sep 22, 2021
    ContributorAuthor
    More actions

    Thanks @MPoorter

    I am on the fence on this.

    I can see how useful it is to use abstract classes and inheritance to share tests. And the change would be trivial.

    But your use case:

    • is way less common than someone using protected by mistake with a simple test layout (one single class)
    • would also warn in Sonar (see https://rules.sonarsource.com/java/tag/tests/RSPEC-5786)
    • could be done differently by wrapping the common behaviour (inheritance vs composition)
    • can be safely ignored with the targeted @SuppressWarnings("PMD.JUnit5TestShouldBePackagePrivate") you are already using

    Also, the rule is named JUnit5TestShouldBePackagePrivate. If we stop complaining about protected test methods, we might as well rename it to convey that we only complain about public modifiers on tests.

    What do you think @adangel?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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

    Projects

    No projects

      Milestone

      • 6.35.0

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402775 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.