pmd icon indicating copy to clipboard operation
pmd copied to clipboard

[java] False-Positive: UnnecessaryImport in test code

Open zodac-personal opened this issue 2 years ago • 3 comments

Affects PMD Version: 7.0.0-rc4

Rule: UnnecessaryImport

Description: I am getting false-positives for imports that are being flagged as not used in my test code. This is impacting both static and non-static imports. I haven't see this occur in any other code, only my test classes.

Note, that this seems to occur intermittently. If I execute on just the module containing this code it fails, but if I run on the whole project it passed fine. I am using mvn clean install, then using a profile that executes PMD. However, I see in Github actions that the failures occur there even when running the whole project: https://github.com/zodac/folding-stats/actions/runs/6523823534/job/17714841008

Code Sample demonstrating the issue: https://github.com/zodac/folding-stats/blob/master/testsuite-integration/src/test/java/me/zodac/folding/test/integration/TeamCompetitionStatsTest.java

Expected outcome:

PMD reports a violation at lines 22-40, and also L49, (all of which are imports from my own project, though other classes from my project are not reported as an issue), but they are all being used in the class.

Running PMD through: Maven (3.21.1-pmd-7.0.0-SNAPSHOT)

zodac-personal avatar Oct 15 '23 11:10 zodac-personal

I too am seeing tons of false positives for this check with 7.0.0-rc4. I've been running PMD against one of our projects for more than five years years. With 6.55 I get a clean report, but today I tried upgrading to 7.0.0-rc4 and I get a ton of these false positives. I'm running pmd through ant but as noted I've been doing so successfully for quite a while so I doubt that's the issue.

tombriggsallego avatar Nov 13 '23 17:11 tombriggsallego

Ok so I did some debugging on this and, at least for me, the problem stems from this:

        if (node.getQualifier() == null) {
            OverloadSelectionResult overload = node.getOverloadSelectionInfo();
            if (overload.isFailed()) {
                return null; // todo we're erring towards FPs
            }

which is in UnnecessaryImport.visit(ASTMethodCall node, Object data)

Our code has a bunch of occurrences of method calls that look like this:

            someMethod(argOne, argTwo,
                    new Arg3(SomeEnum.SOME_ENUM_VALUE, 0, ...));

That leads to two "unnecessary import" warnings - one for the SomeEnum class and one for the Arg3 class.

If I change the code to

           x = new Arg3(SomeEnum.SOME_ENUM_VALUE, 0, ...);
            someMethod(argOne, argTwo, x);

both errors go away. But I don't want to change a bunch of our code to quiet warnings. ;)

tombriggsallego avatar Nov 13 '23 18:11 tombriggsallego

Interesting, thanks for looking into this

oowekyala avatar Nov 13 '23 19:11 oowekyala