DEV Community

Stack Labs

How to test @Configuration class in Spring Boot

davinkevin profile image Λ\: Davin Kevin ・2 min read

In Spring Boot, if you look at the official documentation, there is a lot of ways to test things and we end up in the AnnotationMania © which is from my point of view, "too magic for me".

In this article, we will explore an alternative solution which is more readable and simpler to implements.

Like Josh Long said, everything starts in I've just created a simple project without any dependency.

@Configuration Class

Then, I have created this kind of configuration class, which is pretty usual in Spring Boot Projects:

public class ExampleConfiguration {

    ExampleService exampleService() {
        return new ExampleService();


Test the @Configuration Class

I would like to test this class with a very simple configuration. To do that, I choose to use the tooling usually used by libraries in Spring Boot environment.

So, the test will look like this:

class ExampleConfigurationTest {

     * I setup a context runner with the class ExampleConfiguration
     * in it. For that, I use ApplicationContextRunner#withUserConfiguration() 
     * methods to populate the context.
    ApplicationContextRunner context = new ApplicationContextRunner()

    public void should_check_presence_of_example_service() {
         * We start the context and we will be able to trigger
         * assertions in a lambda receiving a
         * AssertableApplicationContext
         */ -> {
             * I can use assertThat to assert on the context
             * and check if the @Bean configured is present
             * (and unique)

With that, you can unit test your @Configuration classes without any problem.

Thanks to the ApplicationContextRunner you will be able to do a lot thing to test your code, like:

  • Add Bean to your context
  • Load AutoConfiguration classes
  • Set properties
  • Modify the ClassLoader to remove some class

And with the AssertableApplicationContext, you will be able to:

  • Check the presence of bean
  • Get Bean from the context
  • Check if the context has failed

Thanks to that, you will be able to unit-test every @Configuration class simply, without complexity 🚀.

You can check out the whole code here

Discussion (0)

Editor guide