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:

  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 @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.

@TestConfiguration
public class WebTesting {
...
@Bean
public WebClient getWebTests(final WebTest.Builder builder) {
// customized for running unit tests
WebTest 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

Copyright ©2025 Educative, Inc. All rights reserved