加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java – Spring Test中未加载配置属性

发布时间:2020-12-15 01:41:31 所属栏目:大数据 来源:网络整理
导读:我有一个Spring Boot应用程序,它有一些配置属性.我正在尝试为某些组件编写测试,并希望从test.properties文件加载配置属性.我无法让它发挥作用. 这是我的代码: test.properties文件(在src / test / resources下): vehicleSequence.propagationTreeMaxSize=1

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

这是我的代码:

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

vehicleSequence.propagationTreeMaxSize=10000

配置属性类:

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 null”表示未设置配置属性类中的属性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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读