Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

spring
testing
springboot
web client

How to use @TestConfigurations annotations using @Import

Marvah Mushtaq

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
}
TestConfiguration using @Import annotation

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.

RELATED TAGS

spring
testing
springboot
web client

CONTRIBUTOR

Marvah Mushtaq
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring