Testing in Spring Boot

Mid-level Always asked 6 min

On this page

The question

What is the difference between @SpringBootTest, @WebMvcTest and @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

Compare

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

Which test annotation to useFor logic in one class, use a plain unit test with no Spring. For a controller and its JSON, use WebMvcTest. For a repository and its SQL, use DataJpaTest. For wiring across layers, use SpringBootTest.What are youtesting?Logic in a class:no SpringController, JSON:@WebMvcTestRepository, SQL:@DataJpaTestAcross layers:@SpringBootTest
Which test annotation to useFor logic in one class, use a plain unit test with no Spring. For a controller and its JSON, use WebMvcTest. For a repository and its SQL, use DataJpaTest. For wiring across layers, use SpringBootTest.What are youtesting?Logic in a class:no SpringController, JSON:@WebMvcTestRepository, SQL:@DataJpaTestAcross layers:@SpringBootTest
Which test annotation to use

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"));
    }
}
A web slice: real controller, mocked service
@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());
    }
}
A JPA slice against the real database engine
How the context cache treats three test classesClass A finds no cached context with its configuration, so Spring starts one and caches it. Class B has the same configuration and reuses it. Class C adds another MockitoBean, which changes the cache key, so Spring starts a second context.Class A: mocksOrderServiceNo match: startscontext 1Class B: same setupSame key: reusescontext 1Class C: one more@MockitoBeanNew key: startscontext 2
How the context cache treats three test classesClass A finds no cached context with its configuration, so Spring starts one and caches it. Class B has the same configuration and reuses it. Class C adds another MockitoBean, which changes the cache key, so Spring starts a second context.Class A: mocksOrderServiceNo match: startscontext 1Class B: same setupSame key: reusescontext 1Class C: one more@MockitoBeanNew key: startscontext 2
How the context cache treats three test classes
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);
    }
}
A JSON slice: only Jackson loads, to pin the API's field names

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.

  1. Count the contexts. Set logging.level.org.springframework.test.context.cache=DEBUG to log cache statistics: hits, misses and size.
  2. Know the cache key. Spring reuses a context only when the configuration matches: classes, profiles, properties and the set of @MockitoBean replacements. Each difference builds a new one.
  3. Find the differences. Classes mock different beans, a few set @TestPropertySource, and three use @DirtiesContext, which throws the context away.
  4. 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 @DirtiesContext and reset state instead.
  5. 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 */ }
One base class gives every integration test the same cache key

How to answer

  • @WebMvcTest skips @Service, @Repository and plain @Component beans.
  • @DataJpaTest uses 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 @SpringBootTest for every test, which makes the suite slow.
  • Expecting a @Service to 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.
  • @MockitoSpyBean wraps an existing bean, as @SpyBean did.

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 @MockitoBean list or @TestPropertySource means a new context.
  • The cache lives in the JVM (Java Virtual Machine), so it only helps tests in the same process.
  • Overusing @DirtiesContext removes the benefit.

See it in the infographic: Full context vs slice start time

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.
  • TestEntityManager helps 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

1. A test uses @WebMvcTest(OrderController.class), and the controller needs an OrderService. There is no mock for it. What happens?
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.
2. You want to check that a custom repository query returns the right rows. Which option fits best?
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.
3. Two test classes have the same @WebMvcTest setup, but one adds a second @MockitoBean. How many contexts start?
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.