Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:


November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:


Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

1. Overview

In our previous guide to @ConfigurationProperties, we learned how to set up and use the @ConfigurationProperties annotation with Spring Boot to work with external configuration.

In this tutorial, we'll discuss how to test configuration classes that rely on the @ConfigurationProperties annotation to make sure that our configuration data is loaded and bound correctly to its corresponding fields.

2. Dependencies

In our Maven project, we'll use the spring-boot-starter and spring-boot-starter-test dependencies to enable the core spring API and Spring's test API. Additionally, we'll use spring-boot-starter-validation as the bean validation dependency:


3. Properties Binding to User Defined POJOs

When working with externalized configuration, we typically create POJOs containing fields that correspond with the matching configuration properties. As we already know, Spring will then automatically bind the configuration properties to the Java classes we create.

To start, let's assume that we have some server configuration inside a properties file called src/test/resources/server-config-test.properties:


We'll define a simple configuration class corresponding to the previous properties file:

@ConfigurationProperties(prefix = "server")
public class ServerConfig {

    private Address address;
    private Map<String, String> resourcesPath;

    // getters and setters

And also the corresponding Address type:

public class Address {

    private String ip;

    // getters and setters

Finally, we'll inject the ServerConfig POJO into our test class, and validate that all of its fields are set correctly:

@EnableConfigurationProperties(value = ServerConfig.class)
public class BindingPropertiesToUserDefinedPOJOUnitTest {

    private ServerConfig serverConfig;

    void givenUserDefinedPOJO_whenBindingPropertiesFile_thenAllFieldsAreSet() {
        assertEquals("", serverConfig.getAddress().getIp());

        Map<String, String> expectedResourcesPath = new HashMap<>();
        expectedResourcesPath.put("imgs", "/root/imgs");
        assertEquals(expectedResourcesPath, serverConfig.getResourcesPath());

In this test, we used the following annotations:

4. @ConfigurationProperties on @Bean Methods

Another way of creating configuration beans is by using the @ConfigurationProperties annotation on @Bean methods.

For example, the following getDefaultConfigs() method creates a ServerConfig configuration bean:

public class ServerConfigFactory {

    @Bean(name = "default_bean")
    @ConfigurationProperties(prefix = "server.default")
    public ServerConfig getDefaultConfigs() {
        return new ServerConfig();

As we can see, we're able to configure the ServerConfig instance using @ConfigurationProperties on the getDefaultConfigs() method, without having to edit the ServerConfig class itself. This can be particularly helpful when working with an external third-party class that has restricted access.

Next, we'll define a sample external property:


Finally, to tell Spring to use the ServerConfigFactory class when loading the ApplicationContext (thus creating our configuration bean), we'll add the @ContextConfiguration annotation to the test class:

@EnableConfigurationProperties(value = ServerConfig.class)
@ContextConfiguration(classes = ServerConfigFactory.class)
public class BindingPropertiesToBeanMethodsUnitTest {

    private ServerConfig serverConfig;
    void givenBeanAnnotatedMethod_whenBindingProperties_thenAllFieldsAreSet() {
        assertEquals("", serverConfig.getAddress().getIp());

        // other assertions...

5. Properties Validation

To enable bean validation in Spring Boot, we must annotate the top-level class with @Validated. Then we add the required javax.validation constraints:

@ConfigurationProperties(prefix = "validate")
public class MailServer {

    private Map<String, @NotBlank String> propertiesMap;

    private MailConfig mailConfig = new MailConfig();

    // getters and setters

Similarly, the MailConfig class also has some constraints:

public class MailConfig {

    private String address;

    // getters and setters

By providing a valid data set:

[email protected]

the application will start normally, and our unit tests will pass:

@EnableConfigurationProperties(value = MailServer.class)
public class PropertyValidationUnitTest {

    private MailServer mailServer;

    private static Validator propertyValidator;

    public static void setup() {
        propertyValidator = Validation.buildDefaultValidatorFactory().getValidator();

    void whenBindingPropertiesToValidatedBeans_thenConstrainsAreChecked() {
        assertEquals(0, propertyValidator.validate(mailServer.getPropertiesMap()).size());
        assertEquals(0, propertyValidator.validate(mailServer.getMailConfig()).size());

Conversely, if we use invalid properties, Spring will throw an IllegalStateException at start-up.

For instance, using any of these invalid configurations:


will cause our application to fail with this error message:

Property: validate.propertiesMap[second]
Reason: must not be blank

Property: validate.mailConfig.address
Value: user1.test
Reason: must be a well-formed email address

Notice that we used @Valid on the mailConfig field to ensure that the MailConfig constraints are checked, even if validate.mailConfig.address isn't defined. Otherwise, Spring will set mailConfig to null and start the application normally.

6. Properties Conversion

Spring Boot properties conversion enables us to convert some properties into specific types.

In this section, we'll start by testing configuration classes that use Spring's built-in conversion. Then we'll test a custom converter that we'll create ourselves.

6.1. Spring Boot's Default Conversion

Let's consider the following data size and duration properties:

# data sizes

# durations

Spring Boot will automatically bind these properties to the matching DataSize and Duration fields defined in the PropertyConversion configuration class:

@ConfigurationProperties(prefix = "convert")
public class PropertyConversion {

    private DataSize uploadSpeed;

    private DataSize downloadSpeed;

    private Duration backupDay;

    private Duration backupHour;

    // getters and setters

We'll check the conversion results:

@EnableConfigurationProperties(value = PropertyConversion.class)
@ContextConfiguration(classes = CustomCredentialsConverter.class)
public class SpringPropertiesConversionUnitTest {

    private PropertyConversion propertyConversion;

    void whenUsingSpringDefaultSizeConversion_thenDataSizeObjectIsSet() {
        assertEquals(DataSize.ofMegabytes(500), propertyConversion.getUploadSpeed());
        assertEquals(DataSize.ofGigabytes(10), propertyConversion.getDownloadSpeed());

    void whenUsingSpringDefaultDurationConversion_thenDurationObjectIsSet() {
        assertEquals(Duration.ofDays(1), propertyConversion.getBackupDay());
        assertEquals(Duration.ofHours(8), propertyConversion.getBackupHour());

6.2. Custom Converters

Now let's imagine that we want to convert the convert.credentials property:


into the following Credential class:

public class Credentials {

    private String username;
    private String password;

    // getters and setters

To achieve this, we can implement a custom converter:

public class CustomCredentialsConverter implements Converter<String, Credentials> {

    public Credentials convert(String source) {
        String[] data = source.split(",");
        return new Credentials(data[0], data[1]);

Finally, we'll add a Credentials field to the PropertyConversion class:

public class PropertyConversion {
    private Credentials credentials;
    // ...

In our SpringPropertiesConversionUnitTest test class, we also need to add @ContextConfiguration to register the custom converter in Spring's context:

// other annotations
public class SpringPropertiesConversionUnitTest {
    void whenRegisteringCustomCredentialsConverter_thenCredentialsAreParsed() {
        assertEquals("user", propertyConversion.getCredentials().getUsername());
        assertEquals("123", propertyConversion.getCredentials().getPassword());

As the previous assertions show, Spring has used our custom converter to parse the convert.credentials property into a Credentials instance.

7. YAML Documents Binding

For hierarchical configuration data, YAML configuration could be more convenient. YAML also supports defining multiple profiles inside the same document.

The following application.yml located under src/test/resources/ defines a “test” profile for the ServerConfig class:

      on-profile: test
    imgs: /etc/test/imgs
# other profiles

As a result, the following test will pass:

@ContextConfiguration(initializers = ConfigDataApplicationContextInitializer.class)
@EnableConfigurationProperties(value = ServerConfig.class)
public class BindingYMLPropertiesUnitTest {

    private ServerConfig serverConfig;

    void whenBindingYMLConfigFile_thenAllFieldsAreSet() {
        assertEquals("", serverConfig.getAddress().getIp());

        // other assertions ...

A couple of notes regarding the annotations we used:

  • @ContextConfiguration(initializers = ConfigDataApplicationContextInitializer.class) – loads the application.yml file
  • @ActiveProfiles(“test”) – specifies that the “test” profile will be used during this test

Finally, keep in mind that neither @ProperySource nor @TestProperySource support loading .yml files. Therefore, we should always place our YAML configurations within the application.yml file.

8. Overriding @ConfigurationProperties Configurations

Sometimes, we might want to override configuration properties loaded by @ConfigurationProperties with another data set, particularly when testing.

As we've seen in previous examples, we can use @TestPropertySource(“path_to_new_data_set”) to replace the whole original configuration (under /src/main/resources) with a new one.

Alternatively, we could selectively replace some of the original properties using the properties attribute of @TestPropertySource.

Suppose we want to override the previously defined validate.mail_config.address property with another value. All we have to do is annotate our test class with @TestPropertySource, and then assign a new value to the same property via the properties list:

@TestPropertySource(properties = {"[email protected]"})

Consequently, Spring will use the newly defined value:

assertEquals("[email protected]", mailServer.getMailConfig().getAddress());

9. Conclusion

In this article, we learned how to test different types of configuration classes that make use of the @ConfigurationProperties annotation to load .properties and .yml configuration files.

As usual, the source code for this article is available over on GitHub.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:


Junit footer banner
Inline Feedbacks
View all comments
Comments are closed on this article!