【问题标题】:How to make spring boot test app independent of external property source?如何使 Spring Boot 测试应用程序独立于外部属性源?
【发布时间】:2021-08-04 20:10:15
【问题描述】:

我正在为 Spring Boot 应用程序编写控制器测试。要使用 spring 应用程序上下文,我正在使用 SpringRunner 类。 问题是主应用程序类有一个属性源定义到特定文件路径

当我运行测试时,我从硬编码文件中得到一个 FileNotFound 异常。我希望我的测试独立于这个属性源。

我无法在主应用程序中为属性源添加“ignoreResourceNotFound”选项。

下面是定义了属性源的主应用程序类。

@SpringBootApplication
@PropertySource("file:/opt/system/conf/smto/management.properties")
@EnableConfigurationProperties
public class ManagementApp {

    public static void main(String[] args) {
        SpringApplication.run(ManagementApp.class, args);
    }

}

我也在下面添加我的测试类

@RunWith(SpringRunner.class)
@TestPropertySource(locations = {"classpath:application.properties","classpath:management.properties"})
@DirtiesContext
@EmbeddedKafka(topics = {"management-dev"},partitions = 1,
        controlledShutdown = false,brokerProperties = {"listeners=PLAINTEXT://localhost:9092", "port=9092"})
@AutoConfigureMockMvc
@WebMvcTest(Controller.class)
public class ControllerTest {
}

【问题讨论】:

  • 您好,欢迎您! This 并不是真正的“重复”,但 accepted answer 也是解决您问题的方法。 (你会像@ActiveProfiles("override")一样“装饰”你的测试。)
  • 嗨,谢谢@xerx593!我尝试使用@ActiveProfiles("override"),但主要配置类仍在寻找相同的文件。我所做的更改是,将测试类移动到旧包(因此可以找到主应用程序),在测试类上添加 @ActiveProfile("override),并创建 override.properties。同样的错误

标签: spring spring-boot spring-mvc spring-boot-test spring-test-mvc


【解决方案1】:

我找到了在这种情况下创建弹簧上下文的解决方法。我已经更改了我的测试类包,因此,spring-boot 测试找不到主要的配置类。然后提供创建应用程序上下文所需的所有包。

从 spring 文档 here 中找到此解决方案的参考。

只要您没有明确定义,Spring Boot 的 @*Test 注释就会自动搜索您的主要配置。

搜索算法从包含测试的包开始,直到找到@SpringBootApplication 或@SpringBootConfiguration 注释类。只要您以合理的方式构建代码,通常就能找到您的主要配置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 2016-07-04
    • 2020-10-15
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多