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.
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-testin thetestscope. 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
@WebMvcTestwhen the subject is the web layer. - Use
@DataJpaTestwhen the subject is persistence. - Use
@SpringBootTestwhen 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 webApplicationContextwith 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@AutoConfigureMockMvcor@AutoConfigureWebTestClientfor mock-based web tests.RANDOM_PORT: loads aWebServerApplicationContextand starts the embedded server on a random port.DEFINED_PORT: starts the server on the port fromapplication.properties, or on the default8080.NONE: loads anApplicationContextthroughSpringApplicationwith 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.
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
@Transactionalrollback for tests that run in the same thread, such asMOCKtests and persistence slice tests. - In
RANDOM_PORTandDEFINED_PORTtests, 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@Configurationclass, which is used instead of the application's primary configuration, a nested@TestConfigurationclass 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.
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.0orneo4j: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.
- Declare the container in a
@TestConfiguration(proxyBeanMethods = false)class with a@Beanmethod. - Import that class into the test with
@Import. - Inject the container where the test needs it.
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"));
}
}
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@Containerfields and be aware of which test classes share a configuration. - In Kotlin, mark the container with
@JvmStaticinside acompanion object. - When a test fails only after another test class has run, suspect a cached context holding a stopped container.
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:
@SpringBootTestand the other@…Testannotations 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









