相关疑难解决方法(0)

使用YAML的Spring @PropertySource

Spring Boot允许我们用YAML等价物替换我们的application.properties文件.但是我的测试似乎遇到了麻烦.如果我注释我的TestConfiguration(一个简单的Java配置),它期望一个属性文件.

例如,这不起作用: @PropertySource(value = "classpath:application-test.yml")

如果我在我的YAML文件中有这个:

db:
  url: jdbc:oracle:thin:@pathToMyDb
  username: someUser
  password: fakePassword
Run Code Online (Sandbox Code Playgroud)

我会用这样的东西来利用这些价值观:

@Value("${db.username}") String username
Run Code Online (Sandbox Code Playgroud)

但是,我最终得到了错误:

Could not resolve placeholder 'db.username' in string value "${db.username}"
Run Code Online (Sandbox Code Playgroud)

我如何在测试中利用YAML的优点?

spring spring-boot

89
推荐指数
8
解决办法
9万
查看次数

@TestPropertySource在Spring 1.2.6中使用AnnotationConfigContextLoader进行JUnit测试不起作用

看起来我在Spring 4.1.1中使用Spring Boot 1.2.6.RELEASE做的事情根本不起作用.我只是想访问应用程序属性并在必要时使用测试覆盖它们(不使用hack手动注入PropertySource)

这不起作用..

@TestPropertySource(properties = {"elastic.index=test_index"})
Run Code Online (Sandbox Code Playgroud)

这也不是..

@TestPropertySource(locations = "/classpath:document.properties")
Run Code Online (Sandbox Code Playgroud)

也不是..

@PropertySource("classpath:/document.properties")
Run Code Online (Sandbox Code Playgroud)

完整测试案例..

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
@TestPropertySource(properties = {"elastic.index=test_index"})
public class PropertyTests {
    @Value("${elastic.index}")
    String index;

    @Configuration
    @TestPropertySource(properties = {"elastic.index=test_index"})
    static class ContextConfiguration {
    }

    @Test
    public void wtf() {
        assertEquals("test_index", index);
    }
}
Run Code Online (Sandbox Code Playgroud)

导致

org.junit.ComparisonFailure: 
Expected :test_index
Actual   :${elastic.index}
Run Code Online (Sandbox Code Playgroud)

似乎3.x和4.x之间存在很多相互矛盾的信息,我找不到任何可行的信息.

任何见解将不胜感激.干杯!

java junit spring spring-boot

26
推荐指数
5
解决办法
7万
查看次数

标签 统计

spring ×2

spring-boot ×2

java ×1

junit ×1