如何配置最新Spring Boot应用使其启动前自动运行所有单元测试
解决方案
前置问题修复:统一单元测试依赖
你当前项目同时引入了JUnit4和JUnit5(spring-boot-starter-test默认内置JUnit5),会导致部分测试类无法被识别执行,先完成基础调整:
- 调整pom依赖配置,可根据需求选择统一JUnit版本或同时兼容两个版本:
<dependencies> <!-- 其余依赖保持不变 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <!-- 如果要统一使用JUnit4,加上这个排除配置 --> <exclusions> <exclusion> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <!-- 如果要同时兼容JUnit4和JUnit5,替换上面的排除配置为新增这个依赖即可 <dependency> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> <scope>test</scope> </dependency> --> </dependencies>
- 修复测试类错误,删除
DemoApplicationTests里的main测试方法(该方法会直接启动Spring Boot应用,阻塞测试流程),同时对齐JUnit版本的注解:
package com.example.demo; import org.assertj.core.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class DemoApplicationTests { @Autowired private School school; @Test public void contextLoads() { school.setName("test"); String schoolName = school.getName(); Assertions.assertThat(schoolName).isNotNull(); } }
核心配置:实现启动应用前自动执行测试
根据使用场景选择对应方案即可:
方案1:开发场景直接用Maven命令(无需额外配置)
直接执行以下命令,Maven会按生命周期先跑完所有单元测试,测试全部通过才会启动应用:
mvn test spring-boot:run
只要有任意一个测试用例执行失败,流程会直接终止,不会启动应用。
方案2:绑定Maven生命周期,简化执行命令
修改pom的插件配置,把应用启动绑定到测试阶段之后,后续只需要执行mvn test就会自动完成「测试执行→应用启动」的流程:
<build> <plugins> <!-- 配置测试执行插件,保证所有测试类被扫描 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.2</version> <configuration> <includes> <include>**/*Tests.java</include> </includes> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <id>auto-run-after-test</id> <phase>test</phase> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
方案3:打包部署场景
如果是打包为jar包后部署的场景,可在启动脚本中加入测试校验逻辑,Linux脚本示例:
#!/bin/bash # 先执行所有单元测试 mvn test if [ $? -eq 0 ]; then echo "所有单元测试通过,开始启动应用" java -jar target/demo-0.0.1-SNAPSHOT.jar else echo "单元测试未通过,终止应用启动" exit 1 fi
不建议在业务代码中直接调用测试逻辑,测试依赖默认scope为test,不会被打包到生产jar包中,会触发类找不到异常
内容的提问来源于stack exchange,提问作者sampathlk
相关产品推荐
相关产品推荐

