Ensure that fields with specific annotations are &

2019-08-11 07:23发布

问题:

Very common mistake in our code is to write

@Mock Object object;
@InjectMocks Subject subject;

instead of

@Mock private Object object;
@InjectMocks private Subject subject;

This prevents PMD/FindBugs/IntelliJ from issuing warning when the field becomes unused and also our code reviews are bloated with "make this field private" comments.

Is there any static-analysis rule in any tool to warn when fields with specific annotations do not have expected visibility?

I found Checkstyle's VisibilityModifier, but it marks all non-private fields, not just the ones with specific annotations.

回答1:

You could use the Structural Search Inspection in IntelliJ IDEA. For example with a pattern like this:

@Mock @Modifier("packageLocal") $FieldType$ $FieldName$ = $Init$;

FieldType: min: 1, max: 1
FieldName: min: 1, max: 1
Init: min: 0, max: 1



回答2:

You could use PMD's Rule Designer to create a new XPath rule, which can be embedded into a PMD ruleset xml file. I haven't used PMD with IntelliJ IDEA or Jenkins, but I'm sure the plugins exist.

Here's a rule I've made (not tested outside the Rule Designer):

<rule  name="NonPrivateMockAnnotation"
  message="Mock anotation should be private"
  class="net.sourceforge.pmd.lang.rule.XPathRule">
  <description>
  </description>
  <properties>
    <property name="xpath">
    <value>
<![CDATA[
//ClassOrInterfaceBodyDeclaration[
    Annotation/MarkerAnnotation/Name[
        @Image = 'InjectMocks' or
        @Image = 'Mock' 
    ] and
    FieldDeclaration/@Private = 'false'
]
]]>
    </value>
    </property>
  </properties>
  <priority>3</priority>
  <example>
<![CDATA[
class Example {
  @Mock Object object;
  @InjectMocks Subject subject;
}
]]>
  </example>
</rule>