JUnit4测试类以IT结尾不执行改为Test后缀可正常运行原因咨询
问题场景
使用JUnit4运行测试,测试类存放在项目test/java/com/example路径下,测试类代码如下:
@ContextConfiguration(locations = {"classpath:META-INF/spring/test-config.xml"}) @RunWith(SpringJunit4ClassRunner.class) public class ProductIT{ @Autowried private ProductServiceImpl serviceImpl; @Test public void test() throws Exception{ assertNotNull(serviceImpl); } }
项目pom.xml配置如下:
<dependencyManagement> <dependency> <groupId>org.springframework.batch</groupId> <artifactId>spring-batch-core</artifactId> <version>4.2.4-RELEASE</version> </dependency> <dependency> <groupId>org.springframework.batch</groupId> <artifactId>spring-batch-infrastructure</artifactId> <version>4.2.4-RELEASE</version> </dependency> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-batch</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
执行mvn clean install命令构建项目时,命名为ProductIT.java的测试类未被识别不会运行,重命名为ProductTest.java后测试正常执行。
根本原因
这个差异是Maven默认测试插件的命名约定导致的:
Maven默认使用maven-surefire-plugin执行单元测试,该插件内置的默认测试类匹配规则为:
- 类名以
Test开头 - 类名以
Test结尾 - 类名以
TestCase结尾
而后缀为IT的类是Maven约定的集成测试类标识,默认归maven-failsafe-plugin负责在集成测试阶段执行,不会被单元测试阶段的maven-surefire-plugin识别。
你当前的pom.xml中没有额外修改maven-surefire-plugin的匹配规则,也没有引入maven-failsafe-plugin处理集成测试,因此ProductIT.java不会在执行mvn clean install时被运行,重命名为ProductTest.java后符合单元测试的默认命名规则,就可以被正常识别执行。
可选解决方案(如果需要保留IT后缀也能执行)
如果你希望*IT后缀的测试类也能在构建时执行,可以二选其一配置:
- 新增
maven-surefire-plugin配置,增加*IT后缀的匹配规则 - 在pom中引入
maven-failsafe-plugin插件,专门用于执行集成测试类
内容的提问来源于stack exchange,提问作者Neha
相关产品推荐
相关产品推荐

