Skip to content

Grokem · https://www.grokem.com/programming/web-development/backend/spring-boot-testing-best-practices-springboottest-webmvctest-testcontainers

BackendBest practices

Spring Boot testing best practices: @SpringBootTest, @WebMvcTest, Testcontainers

A checklist of standards for testing Spring Boot applications, from plain unit tests and slice annotations to @SpringBootTest and Testcontainers. Each standard gives the reason it matters and how to apply it.

Pankaj Nigam

Technical Writer

Published
  • 11 min read
  • 0 sec

Your progress
  1. Spring Boot testing best practices: @SpringBootTest, @WebMvcTest, Testcontainers11 min(finished)
    0%

A Spring Boot application is a Spring ApplicationContext, so testing it needs nothing special beyond what you do with a vanilla Spring context. The catch is that external properties, logging and other Spring Boot features are installed in the context only when SpringApplication creates it. @SpringBootTest exists for that reason: it builds the test context through SpringApplication.

This checklist gives you eleven standards. Each one states Why it matters and How to apply it. The versions are not pinned here: check the official Spring Boot reference for the release you use, because annotation packages and attribute details can differ between releases.

The official Testing Spring Boot Applications page is the authority on what each slice annotation configures. This guide names @WebMvcTest and @DataJpaTest as slice tests, but it does not restate their exact auto-configuration. Read that page for the list of slice annotations and what each one loads.

more context, slower@SpringBootTest (RANDOM_PORT)+ Testcontainers@SpringBootTest (MOCK)Slice test(@WebMvcTest, @DataJpaTest)Plain unit test(new + mocks)
Start at the bottom and climb only when the test needs more context.

Standard 1: Test plain objects without Spring first

Why. One of the major advantages of dependency injection is that your code becomes easier to unit test. You can create objects with the new operator and never involve Spring. A test that does not start a context is the cheapest and fastest test you can write.

How.

  • Instantiate the class directly and pass its dependencies to the constructor.
  • Replace real collaborators with mock objects.
  • Keep these tests free of any Spring annotation.
  • Add spring-boot-starter-test in the test scope. It brings in the Spring Boot test modules, plus JUnit, AssertJ, Hamcrest and other useful libraries.

Move to a Spring context only when the behaviour you test depends on wiring, configuration or a framework feature.

Standard 2: Pick a slice annotation before @SpringBootTest

Why. Spring Boot provides @SpringBootTest plus a number of other annotations for testing more specific slices of an application. @WebMvcTest and @DataJpaTest are two of them. A slice tests one layer, so you avoid loading everything for a test that needs one layer.

How.

  • Use @WebMvcTest when the subject is the web layer.
  • Use @DataJpaTest when the subject is persistence.
  • Use @SpringBootTest when you need the whole application wired together.
  • Open the official Testing Spring Boot Applications page to see which beans each slice loads. This guide does not repeat that list.

You do not need to add @ExtendWith(SpringExtension.class). @SpringBootTest and the other @…Test annotations are already annotated with it when you use JUnit 6.

Standard 3: Choose webEnvironment on purpose

Why. By default @SpringBootTest does not start a server. The webEnvironment attribute decides how real the web environment is, and a real server costs more time and brings threading effects.

How. Pick one of the four values:

  • MOCK (default): loads a web ApplicationContext with a mock web environment. Embedded servers are not started. If no web environment is on the classpath, it falls back to a regular non-web context. Combine it with @AutoConfigureMockMvc or @AutoConfigureWebTestClient for mock-based web tests.
  • RANDOM_PORT: loads a WebServerApplicationContext and starts the embedded server on a random port.
  • DEFINED_PORT: starts the server on the port from application.properties, or on the default 8080.
  • NONE: loads an ApplicationContext through SpringApplication with no web environment at all.

Prefer MOCK for most web tests and RANDOM_PORT when you need a real HTTP round trip. Avoid DEFINED_PORT unless a fixed port is required, because a busy port breaks the run.

With RANDOM_PORT, Spring Boot also starts the management server on a separate random port if your application uses a different port for it. Remember this when you call management endpoints.

java
import org.junit.jupiter.api.Test;

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class MyRandomPortTests {

    @Test
    void contextLoadsWithRealServer() {
        // call the server on its random port and assert on the response
    }

}

Standard 4: Never rely on @Transactional rollback with a real server

Why. A @Transactional test rolls back at the end of each test method by default. With RANDOM_PORT or DEFINED_PORT you get a real servlet environment, so the HTTP client and the server run in separate threads and separate transactions. Any transaction started on the server does not roll back. Data leaks into the next test and causes order-dependent failures.

How.

  • Keep @Transactional rollback for tests that run in the same thread, such as MOCK tests and persistence slice tests.
  • In RANDOM_PORT and DEFINED_PORT tests, clean up the data you create yourself, or use a throwaway container per run.
  • Write each test so it does not depend on data left behind by another test.

Standard 5: Let configuration detection work, and use @TestConfiguration for additions

Why. Spring Boot's @*Test annotations search for your primary configuration automatically when you do not define one. The search goes up from the package that contains the test until it finds a class annotated with @SpringBootApplication or @SpringBootConfiguration. Explicit @ContextConfiguration(classes=…) or nested @Configuration classes are often not required and can replace the configuration you wanted to test.

How.

  • Keep your tests in the same package tree as your main application class.
  • Do not add @ContextConfiguration(classes=…) unless you have a specific reason.
  • When you need extra beans for a test, use @TestConfiguration. Unlike a nested @Configuration class, which is used instead of the application's primary configuration, a nested @TestConfiguration class is used in addition to it.
  • Do not put settings that belong to one area, such as an extra component scan, on the main method's application class. When you run a slice test, those settings affect it, and the underlying component scan configuration is shared.

Standard 6: Set the web application type when both MVC and WebFlux are present

Why. If Spring MVC is available, Spring Boot configures an MVC-based context. If you have only WebFlux, it configures a WebFlux context. If both are present, Spring MVC takes precedence. A reactive test can then run against the wrong kind of context.

How. Set the spring.main.web-application-type property to reactive in the test.

java
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest(properties = "spring.main.web-application-type=reactive")
class MyWebFluxTests {
    // ...
}

Standard 7: Test persistence against a real service with Testcontainers

Why. Testcontainers manages services that run inside Docker containers and integrates with JUnit. It suits integration tests that talk to a real backend such as MySQL, MongoDB or Cassandra. A real backend catches differences that an in-memory substitute hides.

How.

  • Make sure Docker runs on every machine and CI agent that executes these tests.
  • Name the exact image tag in code, for example mongo:5.0 or neo4j:5, so every run uses the same service.
  • Reserve these tests for behaviour that needs the real service, and keep the rest in faster slice tests.

Standard 8: Declare containers as Spring beans

Why. Containers provided by Testcontainers can be managed by Spring Boot as beans. A container that is a bean belongs to the application context, so its lifecycle follows the context. This avoids the stopped-container problem in Standard 9. The official page notes that this method is often combined with service connection annotations. Check the Testcontainers page of the Spring Boot reference for those annotations, because this guide does not cover them.

How.

  1. Declare the container in a @TestConfiguration(proxyBeanMethods = false) class with a @Bean method.
  2. Import that class into the test with @Import.
  3. Inject the container where the test needs it.
java
import org.testcontainers.mongodb.MongoDBContainer;
import org.testcontainers.utility.DockerImageName;

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;

@TestConfiguration(proxyBeanMethods = false)
class MyTestConfiguration {

    @Bean
    MongoDBContainer mongoDbContainer() {
        return new MongoDBContainer(DockerImageName.parse("mongo:5.0"));
    }

}
java
import org.junit.jupiter.api.Test;
import org.testcontainers.mongodb.MongoDBContainer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;

@SpringBootTest
@Import(MyTestConfiguration.class)
class MyIntegrationTests {

    @Autowired
    private MongoDBContainer mongo;

    @Test
    void myTest() {
        // use the injected container here
    }

}

Standard 9: Respect the context cache when you use the JUnit extension

Why. Testcontainers also offers a JUnit extension. You activate it with @Testcontainers and mark static container fields with @Container. With this extension, containers stop after the test class has run (static fields) or after each test method (non-static fields). Spring's TestContext Framework may cache the ApplicationContext beyond that point and reuse it for another class or method with the same configuration. If the cached context holds beans that depend on a container that has already stopped, later tests can fail. The official page describes this problem in full.

How.

  • Prefer container beans (Standard 8) when several test classes share a context configuration.
  • If you keep the extension, use static @Container fields and be aware of which test classes share a configuration.
  • In Kotlin, mark the container with @JvmStatic inside a companion object.
  • When a test fails only after another test class has run, suspect a cached context holding a stopped container.
java
import org.junit.jupiter.api.Test;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.neo4j.Neo4jContainer;

import org.springframework.boot.test.context.SpringBootTest;

@Testcontainers
@SpringBootTest
class MyExtensionTests {

    @Container
    static Neo4jContainer neo4j = new Neo4jContainer("neo4j:5");

    @Test
    void myTest() {
        // the container starts before any test in this class runs
    }

}

Standard 10: Never hard-code container ports

Why. Containers usually map their internal ports to ephemeral ports on your machine. A Postgres server may listen on 5432 inside the container and on a completely different port locally. Spring Boot's service connections discover and use the locally mapped port. Connection details from a service connection take precedence over connection-related configuration properties, so a fixed port in application.properties will not help and can mislead you.

How.

  • Do not write container ports into test properties.
  • Let service connections or the container bean supply the connection details.
  • Keep Docker Compose support (spring-boot-docker-compose) for development time. The official Development-time Services page describes it as meant for development and disabled when the application is deployed.

Standard 11: Wire the JUnit integration correctly for your JUnit generation

Why. Test annotations are silently ignored if the Spring extension is not active. The official page states that with JUnit 4 you must add @RunWith(SpringRunner.class), or the annotations are ignored. With JUnit 6 you do not add the extension yourself.

How.

  • On JUnit 4, add @RunWith(SpringRunner.class) to each Spring test class.
  • On JUnit 6, add nothing: @SpringBootTest and the other @…Test annotations already carry @ExtendWith(SpringExtension.class).
  • If an injected field is null, check this first.

Checklist

  • Test plain classes with new and mocks, with no Spring context
  • Use a slice annotation such as @WebMvcTest or @DataJpaTest before @SpringBootTest
  • Set webEnvironment on purpose: MOCK, RANDOM_PORT, DEFINED_PORT or NONE
  • Do not rely on @Transactional rollback in RANDOM_PORT or DEFINED_PORT tests
  • Keep tests under the main application package and use @TestConfiguration for extra beans
  • Set spring.main.web-application-type=reactive when MVC and WebFlux are both present
  • Run real backends with Testcontainers and name the image tag
  • Declare containers as @Bean methods in a @TestConfiguration(proxyBeanMethods = false) class
  • Check the context cache when you use @Testcontainers and @Container
  • Never hard-code container ports
  • Add @RunWith(SpringRunner.class) on JUnit 4

Frequently asked questions

Does @SpringBootTest start a server?

No, not by default. The default webEnvironment is MOCK, which provides a mock web environment and starts no embedded server. Use RANDOM_PORT or DEFINED_PORT for a real server.

Why does my @Transactional test not roll back?

With RANDOM_PORT or DEFINED_PORT the client and server run in separate threads and transactions, so a transaction started on the server does not roll back.

Do I need @ContextConfiguration in a Spring Boot test?

Often not. The @*Test annotations search up from the test package for a class annotated with @SpringBootApplication or @SpringBootConfiguration.

How do I add Testcontainers to a Spring Boot test?

Declare the container as a @Bean in a @TestConfiguration class and import it with @Import, or use @Testcontainers with a static @Container field.

Why does a container-based test fail only when run with other tests?

The JUnit extension stops containers after the class or method, but Spring may reuse a cached ApplicationContext whose beans depend on the stopped container.

References

From Grokem: https://www.grokem.com/programming/web-development/backend/spring-boot-testing-best-practices-springboottest-webmvctest-testcontainers

Finished this article?

How did this strike you?

Be the first to react – it is anonymous.

Community

Questions about this?

Ask in Questions and help and get help from other readers.

Ask a questionBrowse Questions and help

Comments

No comments yet. Share what worked for you, or ask a question.

Keep learning

Picked for this article

Related reading, discussions and learning paths on the same subject.

All in Backend

Learning paths

Learning pathBeginner

Git, tests and delivery

The everyday safety net of a software project: undo mistakes in Git, get out of the three common Git problems, write tests with pytest and run them on every pull request.

4 lessonsabout 43 minStart

Learning pathBeginner

From numbers to decisions

Read an experiment honestly, judge a classifier fairly and show the result clearly: p-values, an A/B test worked end to end, classification metrics, chart choice and dashboards.

5 lessonsabout 25 minStart

Choose what we may use. You can change this at any time with “Privacy choices” at the foot of every page. Details are in the Cookie policy and the Privacy policy.

Strictly necessary

Remembers your theme, the lessons you marked as done and this choice. It stays on your device, tracks nothing and cannot be switched off.

Always on
What exactly is collected, and why

Google Analytics

Collects
The pages you view, your device and browser type, your language, how you reached the site and your approximate location (country and city, worked out from your IP address).
Why
To understand which pages and lessons are used, so we can improve them.
Stored
Two cookies, _ga and _ga_<id>, for up to 2 years. Google acts for us; the data is processed by Google, including outside your country.

Grokem’s own counts

Collects
The pages you open and how long you stay, how far you scroll, where you came from, your device type, browser, screen size, language and time zone. Your IP address is turned into a code that changes every day; it is never stored as it is.
Why
To see how long lessons are read and where readers leave. Not shared with anyone.
Stored
A random visitor ID, a visit ID and the time of your last page view in your browser’s storage (gr_vid, gr_sid, gr_last). No name or email is attached.