You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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后缀的测试类也能在构建时执行,可以二选其一配置:

  1. 新增maven-surefire-plugin配置,增加*IT后缀的匹配规则
  2. 在pom中引入maven-failsafe-plugin插件,专门用于执行集成测试类

内容的提问来源于stack exchange,提问作者Neha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 12:18:04