【问题标题】:Spring Boot integration tests doesn't read properties filesSpring Boot 集成测试不读取属性文件
【发布时间】:2017-07-12 19:50:16
【问题描述】:

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

这种行为的原因是什么?我该如何解决?
任何帮助都非常感谢。

【问题讨论】:

  • ClassToTest 看起来像什么?你有@SpringBootTest 吗?它会猜测您的测试没有作为 Spring Boot 测试运行,因此没有加载应用程序属性。如果发生这种情况,将活动配置文件设置为 test 应该足以让 application-test.properties 加载

标签: java spring spring-boot junit4 properties-file


【解决方案1】:

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

使用以下标记您的测试用例:

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

application-xxxx.properties 是不同“配置文件”属性的命名约定。

这个文件application-xxxx.properties应该放在src/main/resources文件夹中。

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

【讨论】:

    【解决方案2】:

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

    更多信息:查看Override default Spring-Boot application.properties settings in Junit Test

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      • 2018-08-03
      • 2016-04-29
      • 2020-02-25
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      相关资源
      最近更新 更多