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
annotation@TestConfiguration
as a static inner classIn this shot, we will focus on how to use @TestConfigurations
annotations using @Import
in Spring Boot.
@Import
annotationThe @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 WebTesting
with the @TestConfiguration
annotation.
Line 17: We then use the @Import
annotation in our test class.
Line 18: We use ExampleTests
to import this test configuration.
Free Resources