facelessss
facelessss

Reputation: 37

how to test configuration classes that rely on the @ConfigurationProperties annotation?

I want to how to test configuration classes that rely on the @ConfigurationProperties annotation to make sure that my configuration data is loaded and bound correctly to their corresponding fields.

Here is class annotioned by @ConfigurationProperties

@Configuration
@ConfigurationProperties(prefix = "config")
public class SomeConfig {

    private HashMap<String,String> smsTypeMap;

    public HashMap<String, String> getSmsTypeMap() {
        return smsTypeMap;
    }

    public void setSmsTypeMap(HashMap<String, String> smsTypeMap) {
        this.smsTypeMap = smsTypeMap;
    }
}

Here is application.yml:

config:
  smsTypeMap:
    a: aliSmsPlateform
    b: yzxSmsPlateform
    c: mlrtSmsPlateform

I want to test it by unit test. thanks

UPDATE: I try :

@RunWith(SpringRunner.class)
@EnableConfigurationProperties(value = SomeConfig.class)
@TestPropertySource("classpath:application.yml")
public class SomeConfigTest {
    @Autowired
    private SomeConfig someConfig;

    @Test
    public void getSmsTypeMap() {
        //Here someConfig.getSmsTypeMap() return null...
        Assert.assertNotNull(someConfig.getSmsTypeMap());
    }
}

Upvotes: 0

Views: 282

Answers (1)

gaetan224
gaetan224

Reputation: 646

in src/test/resources/config/application.yml add

config:
  smsTypeMap:
    a: 'aliSmsPlateform'
    b: 'yzxSmsPlateform'
    c: 'mlrtSmsPlateform'

then you can have these classes

@SpringBootApplication
@EnableConfigurationProperties({SomeConfig.class})
public class MySpringBootApp {
}


@SpringBootTest(classes = MySpringBootApp.class)
public class PropertiesTest {

    @Autowired
    private SomeConfig properties;

    @Test
    public void assertThatUserMustExistToResetPassword() {

        assertThat(properties).isNotNull();
        assertThat(properties.getSmsTypeMap().get("a")).isEqualTo("aliSmsPlateform");
        assertThat(properties.getSmsTypeMap().get("b")).isEqualTo("yzxSmsPlateform");
        assertThat(properties.getSmsTypeMap().get("c")).isEqualTo("mlrtSmsPlateform");
    }
}

Upvotes: 1

Related Questions