在我的项目中,我有一组非常快的单元测试以及一组较慢的集成、端到端和性能测试。我使用 junit5 标签对它们进行分类,并在我的
pom.xml
中将 maven-surefire-plugin
配置为仅运行速度最快的。然而,当我使用 nexus-staging-maven-plugin
部署到中央时,我也想运行慢速的。目前,我通过在命令行上手动覆盖 groups
系统属性来完成此操作:mvn -Dgroups="fast|slow" clean deploy
。然而,这很容易出错,我想知道是否有一种方法可以自动化它:例如,是否可以根据我是否执行maven-surefire-plugin
或install
自动使用不同的配置deploy
?
是的。这就是执行标签的用途。
要将 maven-surefire-plugin (或任何与此相关的插件)绑定到安装阶段,您可以配置:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
<executions>
<execution>
<id>execution1</id>
<phase>install</phase>
<configuration>
<!-- include your configurations here -->
</configuration>
<goals>
<!-- goals go here -->
</goals>
</execution>
</executions>
</plugin>
您当然可以有多个
execution
条目,因此您可以为部署阶段创建不同的 configuration
。
正如@khmarbaise 的评论中提到的,maven-surefire-plugin 是用于单元测试的默认插件,因此它已经在 Maven 生命周期中具有一些默认绑定。尽管可以禁用这些默认设置,但更好的解决方案是考虑使用 maven-failsafe-plugin。该插件 1) 没有任何默认绑定,2) 专门用于集成测试,3) 配置与 Surefire 插件兼容 >90%(failsafe 是 Surefire 的一个分支)。
总结所有对SiKing的回答的评论:
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
<executions>
<execution>
<!-- reconfigure the default execution from test phase -->
<id>default-test</id>
<configuration>
<excludedGroups>slow</excludedGroups>
</configuration>
<goals>
<goal>test</goal>
</goals>
</execution>
<execution>
<!-- additional execution at the beginning of deploy phase -->
<id>pre-deploy-test</id>
<phase>deploy</phase>
<configuration>
<groups>slow</groups>
</configuration>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<!-- nexus-staging must be placed *AFTER* surefire -->
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<!-- nexus staging config here... -->
</plugin>
<!-- other plugins here... -->
</plugins>
更新:根据此评论,有些人可能认为上述内容滥用了surefire,因此下面是使用
maven-failsafe-plugin
进行预部署测试的版本,不需要“破解”default-test
执行万无一失。
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<excludedGroups>slow</excludedGroups>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>3.1.2</version>
<executions>
<execution>
<id>pre-deploy-tests</id>
<phase>deploy</phase>
<configuration>
<includes>
<include>**/*Test.java</include>
<include>**/*Tests.java</include>
</includes>
<groups>slow</groups>
</configuration>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<!-- nexus-staging must be placed *AFTER* failsafe -->
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<!-- nexus staging config here... -->
</plugin>
<!-- other plugins here... -->
</plugins>