首页 > 解决方案 > Spring 应用程序 - 通过测试属性覆盖应用程序属性

问题描述

我是春天的新手,如果有人能帮助我解决这个问题,我将不胜感激。

我有一个 Spring Boot 应用程序 App1,它分别在主包和测试包中具有以下数据库属性:

src/main/resources/app1.properties

src/test/resources/app1-test.properties

假设 app1.properties 包含 oracle 数据库属性,而 app1-test.properties 包含 h2 数据库属性

通常,当我启动 App1 应用程序时,它会从 app1.properties 中获取属性

我的要求是,当我创建应用程序的测试实例(比如 TestApp1)时,应该选择 app1-test.properties 而不是 app1.properties。

我怎样才能做到这一点?请帮忙。

标签: springspring-boot

解决方案


如果您指的是在为您的应用程序运行测试类时,您可以在类上方包含注释 @ActiveProfiles("test") 以包含 app1-test.properties 配置。

类的顶部应该是这样的:

    @ActiveProfiles("test")
    @ExtendWith(SpringExtension.class)
    @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
    public class YourTestClassName {

推荐阅读