Testing in Spring Boot
Mid-level Always asked 6 min
On this page
The question
What is the difference between@SpringBootTest,@WebMvcTestand@DataJpaTest?
30-second answer
They differ in how much of the application context they load. @SpringBootTest loads everything, so it checks wiring across layers but starts slowest. @WebMvcTest loads only the web layer, with MockMvc, so services must be mocks. @DataJpaTest loads repositories and JPA (Jakarta Persistence API), and rolls back each test. Use a slice for one layer, and a few full tests for how layers fit.
Understand it
Pick a slice and see which beans load
Explore@WebMvcTest loads only the web layer. @MockitoBean supplies OrderService, so the controller starts and MockMvc can call it.
View as text
Three layers of boxes: web, with OrderController and MockMvc; business, with OrderService and a plain component; and data, with OrderRepository and the JPA setup. Each box says real, mock, opt-in or not loaded.
@SpringBootTest loads the whole application, so every layer is real. Add @AutoConfigureMockMvc to get MockMvc.
@WebMvcTest loads only the web layer. @MockitoBean supplies OrderService, so the controller starts and MockMvc can call it.
@WebMvcTest skips @Service beans, so the controller has no OrderService and the context fails to start. A mark reads that the context fails.
@DataJpaTest loads repositories and JPA only, and each test rolls back when it ends.
Three layers of boxes: web, with OrderController and MockMvc; business, with OrderService and a plain component; and data, with OrderRepository and the JPA setup. Each box says real, mock, opt-in or not loaded.
@SpringBootTest loads the whole application, so every layer is real. Add @AutoConfigureMockMvc to get MockMvc.
@WebMvcTest loads only the web layer. @MockitoBean supplies OrderService, so the controller starts and MockMvc can call it.
@WebMvcTest skips @Service beans, so the controller has no OrderService and the context fails to start. A mark reads that the context fails.
@DataJpaTest loads repositories and JPA only, and each test rolls back when it ends.
Takeaway: A slice loads one layer and leaves the rest out, so it starts faster, but anything that layer needs from outside must be supplied as a mock.
Full context vs slice start time
CompareFull context: the first class starts every layer, including JPA and messaging. A second class with the same configuration reuses the cached context.
View as text
Two timelines, one per test class. Each shows the parts of the application context that start, then a short block for running the tests. Three rows below say what loads, what the second class does, and what is mocked. Bar lengths compare parts and are not measurements.
Full context: the first class starts every layer, including JPA and messaging. A second class with the same configuration reuses the cached context. The first class starts Web, App, JPA, Kafka; the second class starts nothing.
Web slice: only the web layer starts, so the first class waits far less. Services are mocks, and a second class with the same setup reuses the context. The first class starts Web; the second class starts nothing.
New mock set: a different @MockitoBean list changes the cache key, so the second class starts its own context. Many mock sets can cost more than one full context. The first class starts Web; the second class starts Web.
Two timelines, one per test class. Each shows the parts of the application context that start, then a short block for running the tests. Three rows below say what loads, what the second class does, and what is mocked. Bar lengths compare parts and are not measurements.
Full context: the first class starts every layer, including JPA and messaging. A second class with the same configuration reuses the cached context. The first class starts Web, App, JPA, Kafka; the second class starts nothing.
Web slice: only the web layer starts, so the first class waits far less. Services are mocks, and a second class with the same setup reuses the context. The first class starts Web; the second class starts nothing.
New mock set: a different @MockitoBean list changes the cache key, so the second class starts its own context. Many mock sets can cost more than one full context. The first class starts Web; the second class starts Web.
Takeaway: A slice starts less, and Spring caches a context between test classes with the same configuration, so varying mocks per class can waste what the slice saved.
In code
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired MockMvc mvc;
@MockitoBean OrderService service; // without it, the context fails to start
@Test
void returnsTheOrderCount() throws Exception {
when(service.count()).thenReturn(42);
mvc.perform(get("/orders/count"))
.andExpect(status().isOk())
.andExpect(content().string("42"));
}
}@DataJpaTest // each test runs in a transaction that rolls back
@AutoConfigureTestDatabase(replace = Replace.NONE) // keep the configured database, not an embedded one
class OrderRepositoryTest {
@Autowired OrderRepository orders;
@Test
void findsOrdersByCustomer() {
orders.save(new Order("ana", 20));
assertEquals(1, orders.findByCustomer("ana").size());
}
}record OrderView(long id, @JsonProperty("total_cents") long totalCents) {}
@JsonTest
class OrderViewJsonTest {
@Autowired JacksonTester<OrderView> json;
@Test
void writesTotalInCents() throws Exception {
assertThat(json.write(new OrderView(42, 1999))).extractingJsonPathNumberValue("$.total_cents").isEqualTo(1999);
}
}Solve it
The test suite starts 14 Spring contexts: make it faster
A service has 60 test classes, and the build log shows the Spring banner 14 times; tests take 9 minutes. Most classes use
@SpringBootTest. Find why the contexts are not reused and cut the time.
- Count the contexts. Set
logging.level.org.springframework.test.context.cache=DEBUGto log cache statistics: hits, misses and size. - Know the cache key. Spring reuses a context only when the configuration matches: classes, profiles, properties and
the set of
@MockitoBeanreplacements. Each difference builds a new one. - Find the differences. Classes mock different beans, a few set
@TestPropertySource, and three use@DirtiesContext, which throws the context away. - Remove them. Use slices where a full context is not needed. Give the rest one shared base class with the same
mocks and properties. Drop
@DirtiesContextand reset state instead. - Check. The banner appears two or three times and the suite time drops.
@SpringBootTest
@ActiveProfiles("test")
abstract class IntegrationTestBase {
@MockitoBean PaymentGateway paymentGateway; // the same replacement in every subclass
@MockitoBean MailSender mailSender;
}
class CheckoutIT extends IntegrationTestBase { /* reuses the cached context */ }
class RefundIT extends IntegrationTestBase { /* and so does this one */ }How to answer
@WebMvcTestskips@Service,@Repositoryand plain@Componentbeans.@DataJpaTestuses an embedded database by default, if one is on the classpath.- Logic with no framework needs no annotation at all, only a plain unit test.
- Spring caches contexts, so keep the number of distinct configurations low.
Common mistakes
- Using
@SpringBootTestfor every test, which makes the suite slow. - Expecting a
@Serviceto be injected in a@WebMvcTest.
Follow-up questions
What is MockMvc, and what does it test?
It sends a simulated request through DispatcherServlet with no server or socket. That runs URL mapping, argument binding, validation, JSON conversion, @ControllerAdvice and the status code, none of which a direct call to the controller method would run. It is available in @WebMvcTest, and in @SpringBootTest with @AutoConfigureMockMvc.
- It tests the HTTP contract of a controller, not just the method.
jsonPath("$.id")checks fields in the response body.- No network is involved, so it does not check a real server's settings.
mvc.perform(post("/orders")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"amount\": -1}"))
.andExpect(status().isBadRequest()); See it in the infographic: Pick a slice and see which beans load
What is @MockitoBean, and how is it different from @Mock?
@MockitoBean puts a Mockito mock into the Spring application context, adding the bean or replacing the existing one, so anything wired by Spring receives it. @Mock only creates an object in the test class, with no context involved. Use @Mock in plain unit tests. @MockitoBean came with Spring Framework 6.2 and replaces Spring Boot's deprecated @MockBean.
- It is reset after each test method by default.
- Each different set of mocks changes the context cache key.
@MockitoSpyBeanwraps an existing bean, as@SpyBeandid.
See it in the infographic: Pick a slice and see which beans load See it in the infographic: Full context vs slice start time
How does Spring keep integration tests from starting a new context every time?
The TestContext framework caches application contexts in a static map, keyed by the test's configuration: classes, profiles, properties and mocked beans. A class with the same key reuses the context, so only the first class pays for startup. Anything that changes the key starts another context, and @DirtiesContext throws one away. A shared base test class is a common way to keep one key.
- A different
@MockitoBeanlist or@TestPropertySourcemeans a new context. - The cache lives in the JVM (Java Virtual Machine), so it only helps tests in the same process.
- Overusing
@DirtiesContextremoves the benefit.
Which database does a @DataJpaTest run against?
By default, an embedded database such as H2 replaces your configured DataSource, and each test rolls back in a transaction. That is fast, but SQL that only works on your real engine can fail or pass wrongly. Add @AutoConfigureTestDatabase(replace = Replace.NONE) and point it at a real database, usually with Testcontainers. Call flush() when you need the SQL to run before the rollback.
- With no embedded database on the classpath, the default setup fails to start.
- Without a flush, some writes never reach the database before rollback.
TestEntityManagerhelps set up data for the test.
See it in the infographic: Pick a slice and see which beans load
A @WebMvcTest fails with NoSuchBeanDefinitionException for a service. Why, and how do you fix it?
The slice loads the controller but not @Service beans, so the controller's constructor has nothing to receive. Add @MockitoBean for that service. Do not add @Import of the real service unless you want it in the test, since that pulls in its own dependencies too. If the error names a bean unrelated to this controller, check for extra beans declared on the @SpringBootApplication class.
- Name the controller,
@WebMvcTest(OrderController.class), to avoid loading the others. - Beans declared on the main class load in every slice, so move them to a
@Configuration. - The failure comes at context startup, before any test runs.
See it in the infographic: Pick a slice and see which beans load
Does @SpringBootTest start a real server?
Not by default. The default webEnvironment is MOCK, which uses a mock servlet environment and no port. Use RANDOM_PORT or DEFINED_PORT to start a real embedded server and call it with TestRestTemplate or WebTestClient.
Why doesn't @Transactional roll back a RANDOM_PORT test?
The test and the server run on different threads, and a transaction is bound to one thread. The test's transaction rolls back, but the request ran in its own, which already committed. Clean up data explicitly, or use a slice or the MOCK environment, where the test thread handles the request.
What does @WebMvcTest include besides controllers?
The web infrastructure around them: @ControllerAdvice, filters, WebMvcConfigurer beans, converters and Jackson. Security filter chains apply too, so requests may need @WithMockUser. With no class named, it loads every controller, so each one's dependencies must be mocked.
Check yourself
Show answers
- The context fails to start.: Correct. The slice does not load @Service beans, so the constructor has nothing to inject.
- Spring loads the real OrderService.: Incorrect. A web slice leaves @Service beans out on purpose.
- The controller runs with a null service.: Incorrect. Spring refuses to create a bean with a missing required dependency.
Show answers
- @DataJpaTest: Correct. It loads repositories and JPA and runs the real query, with nothing else slowing the start.
- @WebMvcTest: Incorrect. It does not load repositories at all.
- A unit test with a mocked repository: Incorrect. A mock never runs the query, so it cannot show the query is right.
Show answers
- Two: Correct. The set of mocked beans is part of the cache key, so the second class cannot reuse the first context.
- One: Incorrect. They would share one only if the configuration were identical.
- One per test method: Incorrect. A context is cached across methods and classes; it does not restart per method.