执行mvn clean install时Groovy测试用例不运行仅Java用例执行
Maven构建时仅执行Java测试,Groovy测试不运行
项目里同时写了Java和Groovy(Spock)测试用例,单独跑Groovy测试没问题,但执行mvn clean install时只有Java测试被执行。以下是POM中的相关配置:
<dependency> <groupId>org.spockframework</groupId> <artifactId>spock-core</artifactId> <version>2.4-M1-groovy-4.0</version> <scope>test</scope> </dependency> <!-- Compiles Groovy code. --> <plugin> <groupId>org.codehaus.gmavenplus</groupId> <artifactId>gmavenplus-plugin</artifactId> <version>1.12.1</version> <executions> <execution> <goals> <goal>compileTests</goal> </goals> </execution> </executions> </plugin> <!-- Run Spock Tests --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0</version> <configuration> <useFile>false</useFile> <includes> <include>*.*</include> </includes> </configuration> <!-- Run Spock tests with JUnit not TestNG --> <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit47</artifactId> <version>3.0.0</version> </dependency> </dependencies> </plugin>
问题根源
- Groovy测试编译未绑定正确阶段:当前gmavenplus-plugin仅配置了
compileTests目标,但未明确绑定到test-compile阶段,可能导致Maven执行测试前未编译Groovy测试代码,Surefire插件找不到对应测试类。 - Surefire插件适配错误:Spock 2.x基于JUnit 5平台,而当前使用的
surefire-junit47是JUnit 4的适配包,两者不兼容,导致Spock测试无法被识别。 - 缺少Groovy运行时依赖:Groovy 4.x需要显式引入groovy-all依赖,否则编译后的Groovy类可能无法正常加载。
修复步骤
1. 修正gmavenplus-plugin配置
明确绑定到test-compile阶段,指定Groovy测试代码目录,同时添加Groovy运行时依赖:
<dependency> <groupId>org.spockframework</groupId> <artifactId>spock-core</artifactId> <version>2.4-M1-groovy-4.0</version> <scope>test</scope> </dependency> <!-- 添加Groovy 4.x运行时依赖 --> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>4.0.11</version> <scope>test</scope> <type>pom</type> </dependency> <plugin> <groupId>org.codehaus.gmavenplus</groupId> <artifactId>gmavenplus-plugin</artifactId> <version>1.12.1</version> <executions> <execution> <id>compile-groovy-tests</id> <phase>test-compile</phase> <goals> <goal>compileTests</goal> </goals> </execution> </executions> <configuration> <sources> <source> <directory>${project.basedir}/src/test/groovy</directory> <includes> <include>**/*.groovy</include> </includes> </source> </sources> </configuration> </plugin>
2. 调整Surefire插件适配JUnit 5
更换为surefire-junit-platform适配包,同时明确包含Java和Groovy测试类:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0</version> <configuration> <useFile>false</useFile> <!-- 明确指定要运行的测试类 --> <includes> <include>**/*Test.java</include> <include>**/*Spec.groovy</include> </includes> </configuration> <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit-platform</artifactId> <version>3.0.0</version> </dependency> </dependencies> </plugin>
3. 验证修复
先执行mvn clean test,检查Java和Groovy测试是否都能正常运行;确认无误后再执行mvn clean install即可。
内容的提问来源于stack exchange,提问作者Murugesh Subramaniam
相关产品推荐
相关产品推荐

