in Coding

Testing @ConfigurationProperties in Spring Boot 2.5.X

Three years ago, I wrote an article on how to test Spring’s @ConfigurationProperties classes. Since three years are a long time, I just updated the project on GitHub. It works with Spring 2.5.X now!

You can find the project right here:

And here’s the old post from 2018:

What’s it about?

The basic idea is that you have a configuration class which looks like this:

This class binds to a YAML-configuration file which might look like this:

Eventhough this is a very simple example, how would you test the validation of your configuration class? How would you test that the first property cannot be null and must have atleast 4 characters?

Usually, you would write a test like this:

So what’s wrong with this? Well, you can only test one particular configuration with this. The whole test case loads a single YAML-file and let’s you autowire a single MyConfigurationProperties object. This makes it very annoying to test different variations of a configuration file. You need a whole new test case for each little change. This is where my simple little helper comes into play.

Using a builder for the properties

The project on GitHub shows how to implement a little helper in order to build the configuration properties new in every single test. You can just load any properties file (e.g. application.yml) and manipulate its values to easily create different configurations for your test. This helps to reduce the amount of code you need a lot.

Best regards,

Write a Comment