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:
- Import test configuration using the
@Importannotation - Declare
@TestConfigurationas 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:
@SpringBootTestpublic class UsingStaticInnerTestConfiguration {@TestConfigurationpublic static class WebClientSetting {@Beanpublic WebClient getWebClient(final WebClient.Builder builder) {return builder.baseUrl("http://localhost").build();}}@Autowiredprivate 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
WebClientSettingwith the@TestConfigurationannotation. -
Line 5: We declare a static inner nested class called
WebClientSetting.
Free Resources