Spring 启动集成测试不读取属性文件
Spring Boot integration tests doesn't read properties files
我想创建集成测试,其中 Spring Boot 将使用 @Value 注释从 .properties 文件中读取一个值。
但是每次我 运行 测试我的断言都会失败,因为 Spring 无法读取值:
org.junit.ComparisonFailure:
Expected :works!
Actual :${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:
test=works!
出现这种行为的原因是什么?我该如何解决?
非常感谢任何帮助。
您应该加载应用程序-test.properties 使用@PropertySource 或@TestPropertySource
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(locations="classpath:application-test.properties")
@ContextConfiguration(classes = {WebTests.ConfigurationClass.class, WebTests.ClassToTest.class})
public class WebTests {
}
了解更多信息:查看此
除了上面标出的正确答案外,还有另一种加载应用程序的自然方式-test.properties:将您的测试运行 "profile"设置为"test"。
将您的测试用例标记为:
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
application-xxxx.properties是不同"profile"属性的命名约定。
此文件 application-xxxx.properties 应放在 src/main/resources 文件夹中。
"Profile" 在 bean 配置中也很有用。
我想创建集成测试,其中 Spring Boot 将使用 @Value 注释从 .properties 文件中读取一个值。
但是每次我 运行 测试我的断言都会失败,因为 Spring 无法读取值:
org.junit.ComparisonFailure:
Expected :works!
Actual :${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:
test=works!
出现这种行为的原因是什么?我该如何解决?
非常感谢任何帮助。
您应该加载应用程序-test.properties 使用@PropertySource 或@TestPropertySource
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(locations="classpath:application-test.properties")
@ContextConfiguration(classes = {WebTests.ConfigurationClass.class, WebTests.ClassToTest.class})
public class WebTests {
}
了解更多信息:查看此
除了上面标出的正确答案外,还有另一种加载应用程序的自然方式-test.properties:将您的测试运行 "profile"设置为"test"。
将您的测试用例标记为:
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
application-xxxx.properties是不同"profile"属性的命名约定。
此文件 application-xxxx.properties 应放在 src/main/resources 文件夹中。
"Profile" 在 bean 配置中也很有用。