如何为Spring Boot应用两次运行所有JUnit测试(不同配置值)
让Spring Boot JUnit测试以两种配置各运行一次的方案
下面提供两种实用的实现方式,分别适用于单测试类场景和全局测试场景:
一、单测试类内用JUnit 5参数化测试自动跑两次
如果只是特定测试类需要切换参数验证逻辑,无需修改pom.xml,仅改造测试类即可。核心思路是用JUnit 5的参数化测试特性,配合动态属性注入实现参数切换。
实现代码示例
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.web.servlet.MockMvc; import org.springframework.beans.factory.annotation.Autowired; @WebMvcTest public class DemoControllerTest { @Autowired private MockMvc mockMvc; // 静态变量存当前参数值,供动态属性源使用 private static String currentAbValue; // 动态注入a.b属性 @DynamicPropertySource static void registerAbProperty(DynamicPropertyRegistry registry) { registry.add("a.b", () -> currentAbValue); } // 参数化测试,自动遍历"one"和"two"两个值 @ParameterizedTest @ValueSource(strings = {"one", "two"}) void testWithDifferentAbParams(String abValue) throws Exception { currentAbValue = abValue; // 这里编写你的测试逻辑,比如: // mockMvc.perform(get("/demo")) // .andExpect(status().isOk()) // .andExpect(content().string(containsString(abValue))); } }
注意事项
如果测试上下文被缓存导致参数不生效,可在测试方法上添加@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD),强制每次测试后刷新上下文。
二、通过Maven Profile让所有测试类跑两次
如果需要全部测试类都以两种配置各执行一次,适合用Maven Profile来管理不同参数,通过两次命令触发测试。
1. 修改pom.xml添加Profile
<profiles> <profile> <id>ab-one</id> <properties> <test.ab.value>one</test.ab.value> </properties> </profile> <profile> <id>ab-two</id> <properties> <test.ab.value>two</test.ab.value> </properties> </profile> </profiles>
2. 配置测试用属性文件
在src/test/resources/application-test.yml(或直接在application.yml)中引用Maven参数:
a.b: ${test.ab.value}
3. 执行测试
分别激活两个Profile执行测试,也可合并成一条命令一次性执行:
# 第一次用a.b=one执行所有测试 mvn test -P ab-one # 第二次用a.b=two执行所有测试 mvn test -P ab-two # 或一次性执行两次 mvn test -P ab-one && mvn test -P ab-two
内容的提问来源于stack exchange,提问作者ka3ak
相关产品推荐
相关产品推荐

