Spring 测试中未加载配置属性

Configuration properties are not loaded in Spring Test

我有一个 Spring 启动应用程序,它有一些配置属性。我正在尝试为某些组件编写测试,并希望从 test.properties 文件加载配置属性。我无法让它工作。

这是我的代码:

test.properties 文件(在 src/test/resources 下):

vehicleSequence.propagationTreeMaxSize=10000

配置属性class:

package com.acme.foo.vehiclesequence.config;

import javax.validation.constraints.NotNull;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = VehicleSequenceConfigurationProperties.PREFIX)
public class VehicleSequenceConfigurationProperties {
    static final String PREFIX = "vehicleSequence";

    @NotNull
    private Integer propagationTreeMaxSize;

    public Integer getPropagationTreeMaxSize() {
        return propagationTreeMaxSize;
    }

    public void setPropagationTreeMaxSize(Integer propagationTreeMaxSize) {
        this.propagationTreeMaxSize = propagationTreeMaxSize;
    }
}

我的测试:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = VehicleSequenceConfigurationProperties.class)
@TestPropertySource("/test.properties")
public class VehicleSequenceConfigurationPropertiesTest {

    @Autowired
    private VehicleSequenceConfigurationProperties vehicleSequenceConfigurationProperties;

    @Test
    public void checkPropagationTreeMaxSize() {
        assertThat(vehicleSequenceConfigurationProperties.getPropagationTreeMaxSize()).isEqualTo(10000);
    }
}

测试失败并显示 "Expecting actual not to be null",这意味着未设置配置属性 class 中的 属性 propagationTreeMaxSize

发布问题两分钟后,我找到了答案。

我必须使用 @EnableConfigurationProperties(VehicleSequenceConfigurationProperties.class):

启用配置属性
@RunWith(SpringRunner.class)
@TestPropertySource("/test.properties")
@EnableConfigurationProperties(VehicleSequenceConfigurationProperties.class)
public class VehicleSequenceConfigurationPropertiesTest {

    @Autowired
    private VehicleSequenceConfigurationProperties vehicleSequenceConfigurationProperties;

    @Test
    public void checkPropagationTreeMaxSize() {
        assertThat(vehicleSequenceConfigurationProperties.getPropagationTreeMaxSize()).isEqualTo(10000);
    }
}