Configuration properties are not loaded in Spring Test

lexicore :

I have a Spring Boot application which has some configuration properties. I'm trying to write a test for some of the components and want to load configuration properties from a test.properties file. I can't get it to work.

Here's my code:

test.properties file (under src/test/resources):

vehicleSequence.propagationTreeMaxSize=10000

Configuration properties 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;
    }
}

My test:

@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);
    }
}

The test fails with "Expecting actual not to be null" meaning the property propagationTreeMaxSize in the configuration properties class was not set.

lexicore :

Two minutes after posting the question, I've found the answer.

I had to enable configuration properties with @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);
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=459558&siteId=1