Spring Boot集成测试不会读取属性文件

我想创建集成测试,其中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!"); } } 

src / main / resource包下的application-test.properties包含:

 test=works! 

这种行为的原因是什么?我该如何解决?
任何帮助高度赞赏。

您应该使用@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 { } 

有关更多信息:请查看Junit Test中的Override默认Spring-Boot application.properties设置

除了上面标记的正确答案之外,还有另一种加载application-test.properties的自然方法:将测试运行“profile”设置为“test”。

标记您的测试用例:

 @ActiveProfiles("test") @RunWith(SpringJUnit4ClassRunner.class) 

application-xxxx.properties是不同“profile”属性的命名约定。

“配置文件”在bean配置中也很有用。