[英]Spring Boot integration tests doesn't read properties files
I would like to create integration test in which Spring Boot will read a value from .properties file using @Value annotation.我想创建集成测试,其中 Spring Boot 将使用@Value注释从 .properties 文件中读取一个值。
But every time I'm running test my assertion fails because Spring is unable to read the value:但是每次我运行测试时,我的断言都会失败,因为 Spring 无法读取该值:
org.junit.ComparisonFailure:
Expected :works!
Actual :${test}
My test:我的测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebTests.ConfigurationClass.class, WebTests.ClassToTest.class})
public class WebTests {
@Configuration
@ActiveProfiles("test")
static class ConfigurationClass {}
@Component
static class ClassToTest{
@Value("${test}")
private String test;
}
@Autowired
private ClassToTest config;
@Test
public void testTransferService() {
Assert.assertEquals(config.test, "works!");
}
}
application-test.properties under src/main/resource package contains: src/main/resource 包下的 application-test.properties 包含:
test=works!
What can be the reason of that behavior and how can I fix it?这种行为的原因是什么,我该如何解决?
Any help highly appreciated.任何帮助高度赞赏。
You should load the application-test.properties using @PropertySource or @TestPropertySource您应该使用 @PropertySource 或 @TestPropertySource 加载 application-test.properties
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(locations="classpath:application-test.properties")
@ContextConfiguration(classes = {WebTests.ConfigurationClass.class, WebTests.ClassToTest.class})
public class WebTests {
}
for more info: Look into this Override default Spring-Boot application.properties settings in Junit Test有关更多信息:查看Junit Test 中的 Override default Spring-Boot application.properties 设置
Besides the above marked correct answer, there is another nature way to load application-test.properties: Set your test run "profile" to "test".除了上面标记的正确答案之外,还有另一种加载 application-test.properties 的自然方式:将您的测试运行“配置文件”设置为“测试”。
Mark your test cases with:标记您的测试用例:
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
application-xxxx.properties is a naming convention for properties of different "profile". application-xxxx.properties 是不同“配置文件”属性的命名约定。
This file application-xxxx.properties should be placed in src/main/resources folder.这个文件 application-xxxx.properties 应该放在 src/main/resources 文件夹中。
"Profile" is also useful in bean configuration. “配置文件”在 bean 配置中也很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.