How to use the @TestConfigurations annotations using static class

Overview

We use the @TestConfiguration annotation, which is a unique form of @Configuration, to define additional beans or customized tests.

Although the @TestConfiguration annotation is inherited from the @Configuration annotation, the main difference is that @TestConfiguration is excluded during Spring Boot’s component scanning.

Additional test configuration for tests is included using the following two ways:

  1. Import test configuration using the @Import annotation
  2. Declare @TestConfiguration as a static inner class

In this shot, we will focus on how to use @TestConfigurations annotations using a static inner class.

Using @TestConfiguration with a static inner class

Nested classes inside the test class are used to define the test configurations. The @Configuration or @TestConfiguration annotations represent a nested class.

The @SpringBootTest context will automatically register it and load the test configuration if it is declared as a static inner class:

@SpringBootTest
public class UsingStaticInnerTestConfiguration {
@TestConfiguration
public static class WebClientSetting {
@Bean
public WebClient getWebClient(final WebClient.Builder builder) {
return builder.baseUrl("http://localhost").build();
}
}
@Autowired
private DataService dataService;
// Test methods of dataService
}

Let’s breakdown the code written above:

  • Line 2: We declare a class by using UsingStaticInnerTestConfiguration.

  • Line 4: We annotate WebClientSetting with the @TestConfiguration annotation.

  • Line 5: We declare a static inner nested class called WebClientSetting.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved