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

Spring Boot中@TestPropertySource加载测试配置文件失败问题

解决Spring Boot单元测试加载指定配置文件问题

问题原因

你当前的错误是因为@TestPropertySource中配置的路径错误。Maven/Gradle构建时,src/test/resources下的文件会被复制到测试类路径的根目录(即target/test-classes),所以不需要在classpath路径里加上src/test/resources前缀,否则Spring会找不到对应文件。另外注意代码中配置的文件名是properties-test.yml,但错误提示查找的是test.properties,要确保配置的文件名和实际文件一致。

解决方案

方案1:修正@TestPropertySource的路径

直接指定classpath根目录下的目标配置文件即可:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
// 正确指定classpath下的test.properties
@TestPropertySource(locations = "classpath:test.properties")
public class SecurityConfigurationTest {
    @MockBean
    KafkaConfiguration kafkaConfiguration;

    @MockBean
    KafkaMonitor kafkaMonitor;

    @MockBean
    BuildProperties buildProperties;

    @Autowired
    MockMvc mockMvc;

    @Test
    public void unauthorizedUser_shouldNotAccessHomePage() throws Exception{
        mockMvc
                .perform(get("/"))
                .andExpect(status().isUnauthorized());
    }
}

方案2:利用Spring Boot Profile特性(更推荐)

Spring Boot默认支持按环境加载配置,遵循application-{profile}.properties命名规则:

  1. 将测试配置文件命名为application-test.properties,放在src/test/resources目录下
  2. 在测试类上添加@ActiveProfiles("test"),Spring会自动加载该测试配置,同时覆盖application.properties中的同名配置:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("test") // 激活test环境配置
public class SecurityConfigurationTest {
    // 原有代码不变
}

方案3:完全排除主配置文件(可选)

如果需要完全不加载src/main/resources/application.properties,可以通过指定配置文件名实现:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
// 指定仅加载test.properties,不加载默认的application.properties
@TestPropertySource(properties = "spring.config.name=test")
public class SecurityConfigurationTest {
    // 原有代码不变
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 04:10:35