【问题标题】:Spring Boot Test yml properties not being read in integration tests集成测试中未读取 Spring Boot Test yml 属性
【发布时间】:2018-10-30 01:01:14
【问题描述】:

在以下集成测试中,Spring Boot 无法找到正确的属性文件并读取其值:

@RunWith(SpringRunner.class)
@SpringBootTest()
@ActiveProfiles("embedded")
public class ApiApplicationTests {

    @Autowired
    protected Environment env;

    @Test
    public void contextLoads() {
    }

    @Test
    public void verifyProperty() {
        assertEquals("jdbc:h2:mem:testdb",
                env.getProperty("spring.datasource.url"));
    }
}

基于它选择属性文件application-embedded.yml:

spring:
  h2:
    console:
      enabled: true
  liquibase:
    enabled: true
    change-log: classpath:db/changelog/db.changelog-master.xml
    drop-first: true # should be false in prod but good for dev and test!
  datasource:
    url: jdbc:h2:mem:testdb
    username: h2
    password: h2

security:
  oauth2:
    resource:
      filter-order: 3
  signing-key: MaYzkSjmkzPC57L
  security-realm: AvMaint Realm
  jwt:
    client-id: avmaintwebsitejwtclientid
    client-secret: XY7kmzoNzl100
    grant-type: password
    scope-read: read
    scope-write: write
    resource-ids: avmaintwebsitejwtresourceid

此测试失败,并显示:“java.lang.IllegalStateException:未找到所需的键 'url'”。尽管应用程序似乎可以看到配置文件:

2018-05-20 10:42:36.810  INFO 66697 --- [    Test worker] au.com.avmaint.api.ApiApplicationTests   : The following profiles are active: embedded

看起来,找到配置文件后,它会继续读取“默认”值。

有人知道为什么吗?

另外,我发现通过添加注释

@TestPropertySource("/application-embedded.yml")

我可以强制它使用该文件,但配置文件的意义何在?

【问题讨论】:

    标签: spring-boot spring-boot-test


    【解决方案1】:

    你可以使用@SpringBootTest(classes=YourMainApplicationClassName.class)。希望这将有助于加载您的主类作为入口点,并且还将自行选择所有相关配置(即加载所有配置的应用程序上下文)

    【讨论】:

    • 感谢您查看它,但这不起作用,再次,它只是加载弹簧默认属性。我还认为@SpringBootTest 的意义在于它加载了所有内容而不是@WebMvcTest,不是这样吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    相关资源
    最近更新 更多