PMD maven 插件:如何为测试指定不同的规则集?

问题描述

我需要配置 PMD maven 插件来扫描测试源代码,与生产代码相比,检查不那么严格。

有办法吗?

解决方法

您可能需要为插件配置两个单独的 executions。这允许您使用不同的配置。一次执行仅检查生产代码 (<includeTests>false</includeTests>),其他执行仅检查测试代码(<includeTests>true</includeTests><excludeRoots><excludeRoot>${basedir}/src/main/java</excludeRoot></excludeRoots>)。

如果您分享您的解决方案,我们可以将其作为示例添加到 https://maven.apache.org/plugins/maven-pmd-plugin/

另一种方法是对所有代码使用相同的代码质量规则,避免做出妥协,因为它“只是测试代码”。虽然测试代码不在生产中运行,但它用于测试生产代码,因此如果您使用较不严格的检查,那么您可能会将测试代码视为最薄弱的环节...


以下是此场景的完整插件配置:

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-pmd-plugin</artifactId>
                <version>3.14.0</version>
                <configuration>
                    <includeTests>false</includeTests>
                    <rulesets>
                        <ruleset>config/pmd/pmdMain.xml</ruleset>
                    </rulesets>
                    <linkXRef>false</linkXRef>
                </configuration>
                <executions>
                    <execution>
                        <id>pmd-main</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>check</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>pmd-test</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>pmd</goal>
                            <goal>check</goal>
                        </goals>
                        <configuration>
                            <targetDirectory>${project.build.directory}/pmdTest/</targetDirectory>
                            <includeTests>true</includeTests>
                            <excludeRoots>
                                <excludeRoot>${basedir}/src/main/java</excludeRoot>
                            </excludeRoots>
                            <rulesets>
                                <ruleset>config/pmd/pmdTest.xml</ruleset>
                            </rulesets>
                        </configuration>
                    </execution>
                    <execution>
                        <id>cpd</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>cpd-check</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

它使用规则集 config/pmd/pmdMain.xml 作为主代码,无需测试。这是直接在插件级别配置的。 规则集 config/pmd/pmdTest.xml 仅用于测试代码。这是在执行中使用 id pmd-test 配置的。

不过它有一个缺点:PMD 运行了三遍……主代码运行了两次,测试代码运行了一次。原因是“pmd:check”自动触发“pmd:pmd”,但它只使用标准配置(例如忽略生命周期/执行ID)。

执行“pmd-test”为测试代码调用一次“pmd:pmd”(创建target/pmdTest/pmd.xml),然后调用pmd:check——它本身调用pmd:pmd并使用默认配置- 然后实际运行 pmd:check,它使用执行配置并使用 target/pmdTest/pmd.xml 来决定是否构建失败。