How to use @TestConfigurations annotations using @Import
Overview
We use @TestConfiguration to define additional beans or customizations for a test. This is a unique form of @Configuration.
Although the @TestConfiguration annotation is inherited from the @Configuration annotation, the main difference is that @TestConfiguration is excluded during Spring Boot’s component scanning.
We add the additional test configuration for tests in the following way:
- 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 @Import in Spring Boot.
The @Import annotation
The @Import annotation is a class-level annotation. We use this to import the bean definitions from various classes annotated with the @Configuration annotation or the @TestConfiguration annotation into the application or Spring test context.
@TestConfigurationpublic class WebTesting {...@Beanpublic WebClient getWebTests(final WebTest.Builder builder) {// customized for running unit testsWebTest test = builder.baseUrl("http://localhost").build();......return test;}}@SpringBootTest@Import(WebTesting.class)class ExampleTests {// Test case implementations}
Let’s break down the code:
-
Lines 1–2: We annotate
WebTestingwith the@TestConfigurationannotation. -
Line 17: We then use the
@Importannotation in our test class. -
Line 18: We use
ExampleTeststo import this test configuration.
Free Resources