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

Spring Boot测试类加载ApplicationContext失败问题及解决方法

Spring Boot测试上下文加载失败:Failed to add PropertySource to Environment

问题描述

开发Spring Web应用,完成控制器、Mapper等组件开发后执行测试,自动生成的BankAppApplicationTests类中contextLoads()测试方法执行失败。

测试类代码如下:

@TestPropertySource(locations = {"classpath:application.yaml", "classpath:db/changelog/db.changelog-master-test.xml"})
@SpringBootTest(classes = BankAppApplication.class, properties = {"spring.profiles.active=test"})
class BankAppApplicationTests {

    @Test
    void contextLoads() {
    }
}

项目包含两个application.yaml配置文件,仅数据源URL不同(分别对应主应用数据库与测试数据库),主应用可正常启动,Liquibase能完成数据库创建与数据填充,但测试执行时失败,测试数据库未被初始化,报错信息:

10:59:33.497 [main] ERROR org.springframework.boot.SpringApplication -- Application run failed
java.lang.IllegalStateException: Failed to add PropertySource to Environment

解决步骤

执行以下操作后,测试类成功运行并连接测试数据库:

  • 移除测试类上的@TestPropertySource注解
  • 删除两个application.yaml文件中的spring.profiles.active=default配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 02:34:56