Spring允许我们用YAML等效项替换我们的application.properties文件。然而,我的测试似乎遇到了一个障碍。如果我注释了我的TestConfiguration (一个简单的Java ),它就需要一个属性文件。
例如,这不起作用:@PropertySource(value = "classpath:application-test.yml")
如果我在我的YAML文件中有这样的内容:
db:
url: jdbc:oracle:thin:@pathToMyDb
username: someUser
password: fakePassword我会用这样的方法来利用这些价值:
@Value("${db.username}") String username但是,我最终会出现这样的错误:
Could not resolve placeholder 'db.username' in string value "${db.username}"我如何在我的测试中利用YAML的优点呢?
发布于 2014-11-10 09:29:54
Spring-boot为此提供了一个助手,只需添加
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)在测试类或抽象测试超类的顶部。
编辑:我五年前写了这个答案。它不适用于Spring的最新版本。这就是我现在所做的(如果有必要,请将Kotlin翻译成Java ):
@TestPropertySource(locations=["classpath:application.yml"])
@ContextConfiguration(
initializers=[ConfigFileApplicationContextInitializer::class]
)被添加到顶部,然后
@Configuration
open class TestConfig {
@Bean
open fun propertiesResolver(): PropertySourcesPlaceholderConfigurer {
return PropertySourcesPlaceholderConfigurer()
}
}关于上下文的。
发布于 2016-05-20 14:34:39
如前所述,@PropertySource不加载yaml文件。作为解决办法,自己加载文件并将加载的属性添加到Environment中。
实施ApplicationContextInitializer
public class YamlFileApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
try {
Resource resource = applicationContext.getResource("classpath:file.yml");
YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
PropertySource<?> yamlTestProperties = sourceLoader.load("yamlTestProperties", resource, null);
applicationContext.getEnvironment().getPropertySources().addFirst(yamlTestProperties);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}将初始化程序添加到测试中:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class, initializers = YamlFileApplicationContextInitializer.class)
public class SimpleTest {
@Test
public test(){
// test your properties
}
}发布于 2018-07-18 02:28:27
@PropertySource可以通过factory参数进行配置。所以你可以做这样的事情:
@PropertySource(value = "classpath:application-test.yml", factory = YamlPropertyLoaderFactory.class)其中YamlPropertyLoaderFactory是您的自定义属性加载程序:
public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
if (resource == null){
return super.createPropertySource(name, resource);
}
return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource(), null);
}
}https://stackoverflow.com/questions/21271468
复制相似问题