【问题标题】:How to get properties from .env file in spring boot test如何在春季启动测试中从 .env 文件中获取属性
【发布时间】:2022-08-20 09:44:46
【问题描述】:

我正在尝试为我的 spring-boot 应用程序设置测试。在常规执行中,我从我在运行配置中指定的 .env 文件中获取一些值,并像这样获取它们:

 @Value(\"${jdbc.url}\")
 private String jdbcUrl;

但是当我尝试运行最简单的测试时,它会失败并出现以下异常:

无法加载 ApplicationContext java.lang.IllegalStateException:无法加载应用程序上下文............ 原因:org.springframework.beans.factory.BeanCreationException:创建名称为\'jpaConfig\'的bean时出错:注入自动装配的依赖项失败;嵌套异常是 java.lang.IllegalArgumentException: 无法解析值 \"${jdbc.url}\" 中的占位符 \'jdbc.url\'

如何从 SpringBootTest 中的环境加载属性?

这是我的测试:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {App.class})
public class TestingWebApplicationTest {

    @Test
    public void contextLoads() {
    }

}
  • 为什么不使用 application.properties 文件?

标签: java spring-boot environment-variables junit5


【解决方案1】:

尝试将您的属性添加到此位置 /src/test/resources/application-test.properties

在测试类上添加 @ActiveProfiles("test") 注释,它应该被拾取。 见下面的截图;

You can use a profile specific application-{profile}.properties file

【讨论】:

    猜你喜欢
    • 2018-01-21
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2019-08-17
    • 2016-12-13
    • 2018-07-20
    相关资源
    最近更新 更多