java Spring引导集成测试不读取属性文件
我想创建一个集成测试,SpringBoot将从中读取一个值。使用@Value注释的属性文件
但每次运行测试时,我的断言都会失败,因为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!");
}
}
应用测试。src/main/resource包下的属性包含:
test=works!
这种行为的原因是什么?我该如何解决
非常感谢您的帮助
# 1 楼答案
您应该加载应用程序测试。使用@PropertySource或@TestPropertySource的属性
有关更多信息:请查看此Override default Spring-Boot application.properties settings in Junit Test
# 2 楼答案
除了上面标记的正确答案外,还有另一种加载应用程序测试的自然方法。属性:将测试运行“配置文件”设置为“测试”
使用以下内容标记您的测试用例:
申请表xxxx。属性是不同“配置文件”属性的命名约定
此文件包含应用程序xxxx。属性应该放在src/main/resources文件夹中
“Profile”在bean配置中也很有用