@SpringBootTest未正确加载application-test.yml问题求助
兄弟,我太懂你这种配置不生效的抓狂感了!咱们来一步步拆解这个问题,核心原因其实是Spring Boot测试时没正确切换到test环境的配置,导致它顽固地加载了main目录下的MySQL配置。下面是具体的排查和解决步骤:
问题根源
Spring Boot不会自动在测试时切换到test profile,除非你明确指定。如果没激活test环境,它会默认加载main目录下的配置(比如你可能在main的application-development.yml里设置了默认激活的profile,或者直接用了默认配置),这就是为什么你自定义配置也没用的原因——优先级不对。
解决方案
1. 先给测试类激活test Profile(最关键!)
这一步是核心,你得告诉Spring Boot:“现在我要跑测试,用test环境的配置!”有两种简单方式:
- 方式一:在测试类上加注解
在你的@SpringBootTest测试类上添加@ActiveProfiles("test"),示例代码:@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") // 重点!激活test环境 public class YourIntegrationTest { // 你的测试方法 } - 方式二:在test资源目录加默认配置
在test/resources下创建一个application.yml(或application.properties),里面指定默认激活test profile:# test/resources/application.yml spring: profiles: active: test
2. 确认application-test.yml的正确性
检查你的测试配置文件:
- 位置必须是
test/resources/application-test.yml(注意大小写,Linux/macOS环境下文件名区分大小写) - H2的配置要正确,比如:
# test/resources/application-test.yml spring: datasource: url: jdbc:h2:mem:testdb driver-class-name: org.h2.Driver username: sa password: "" h2: console: enabled: true # 可选,方便测试时打开H2控制台 jpa: hibernate: ddl-auto: create-drop show-sql: true properties: hibernate: dialect: org.hibernate.dialect.H2Dialect
3. 让自定义@TestConfiguration生效
如果还是想用自定义的DataSource,记得给你的TestConf加上@Primary注解,确保它优先于其他DataSource被加载,并且要在激活test profile的前提下引入:
@TestConfiguration public class TestConf { @Bean @Primary // 标记为优先使用的数据源 public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .build(); } }
然后在测试类上通过@Import引入这个配置:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") @Import(TestConf.class) // 引入自定义测试配置 public class YourIntegrationTest { // ... }
4. 检查pom里的H2依赖
确认H2的依赖scope确实是test,这样它只会在测试阶段生效,不会影响主应用:
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency>
5. 排查是否有其他配置覆盖
- 检查main目录下的
application.yml或application-development.yml有没有设置spring.profiles.active=development,如果有,测试时必须用@ActiveProfiles("test")覆盖这个设置 - 检查系统环境变量、JVM启动参数(比如
-Dspring.profiles.active=development),这些优先级比代码注解高,会强制加载指定的profile
验证是否生效
运行测试时,盯着控制台日志,如果你看到类似下面的输出,就说明test环境已经激活了:
The following 1 profile is active: "test"
这时候Spring Boot就会加载test/resources/application-test.yml的配置,而不是main下的MySQL配置了。
内容的提问来源于stack exchange,提问作者hlepme
相关产品推荐
相关产品推荐

