Skip to content

[java] ImmutableField reports fields annotated with @Autowired (Spring) and @Mock (Mockito) #3874

@C-Otto

Description

@C-Otto

Also see my comment in #3855.

Affects PMD Version:
6.44.0

Rule:
ImmutableField
https://pmd.github.io/pmd-6.44.0/pmd_rules_java_design.html#immutablefield

Description:
Fields annotated with Spring's @Autowired are reported as "could be final", although the field needs to be non-final in order for Spring to set it via reflection. While I prefer constructor injection for production code (where this false positive is not triggered), using annotated fields is very common for (integration) tests as shown below. This issue also exist for @Mock (Mockito) and several another annotations.

Note that this seems to be some kind of regression, as I didn't experience this with 6.43.0. I am aware that I can exclude annotations as shown in the documentation, but given the fact that it worked before, I'd like to voice my concerns and let you decide if this is a bug or not.

Code Sample demonstrating the issue:

@DataJpaTest
class SomeRepositoryIT {
    @Autowired
    private SomeRepository repository;

    ...
}

Expected outcome:
PMD reports a violation for field repository, but that's wrong. That's a false positive.

Running PMD through:
Gradle

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematicgood first issueA great starting point for new contributors

    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