首页 > 解决方案 > 如何从 java 测试中排除 META-INF/spring.factories 中的引导

问题描述

在资源/META-INF/spring.factories 中有这一行: org.springframework.cloud.bootstrap.BootstrapConfiguration=org.path.to.AWSConfig

@RunWith(SpringRunner.class)运行 AWSConfig 时使用的集成测试执行失败。测试不需要 AWSConfig 即可运行。在排除 AWSConfig 的 SO 上尝试了许多方法,包括:

但 AWSConfig 仍在运行(并且失败)。如何从测试中排除引导配置类?

测试设置:

@RunWith(SpringRunner.class)
@WebMvcTest(UnitLeaderRequestController.class)
@WithMockUser
public class UnitLeaderRequestControllerTest {
    @Autowired
    MockMvc mvc;
    ...
}

标签: spring-bootspring-testspring-cloud-config

解决方案


快速解决方案:

将此注释添加到测试类排除了引导:

@TestPropertySource(properties={"spring.cloud.bootstrap.enabled = false"})

替代解决方案:

基于如何在 WebMvcTest 中禁用 Eureka 和 Spring Cloud Config?

我将注释更改为@TestPropertySource(locations = "classpath:application-controller-tests.properties")

,在 /resources 中创建 application-controller-tests.properties 并添加spring.cloud.bootstrap.enabled = false到文件中,以便多个测试类可以使用 1 个位置的排除项。

进一步的想法

更好的解决方法可能是完全停止使用 META-INF/spring.factories,并使用 bootstrap-{env}.yml 文件。我不确定从项目中删除 META-INF/spring.factories 的影响。


推荐阅读