Video in progress

Middle 🧪 Testing

How does @SpringBootTest differ from slice tests like @WebMvcTest and @DataJpaTest, and which do you choose when?

@SpringBootTest starts the whole application context: slow, but everything is real. Slice tests load only the beans of one layer: @WebMvcTest loads controllers and MVC, @DataJpaTest loads JPA and repositories. They're faster and pin down a failure more precisely.

📖 Answer

A slice is a piece of the context. Spring Boot turns on only the auto-configurations that are needed:

Annotation What it loads What it doesn't load
@WebMvcTest controllers, @ControllerAdvice, filters, MockMvc, Jackson @Service, @Repository
@DataJpaTest entities, repositories, EntityManager, DataSource web, services
@JsonTest ObjectMapper, JacksonTester almost everything
@RestClientTest the RestClient/RestTemplate builder, MockRestServiceServer anything database-related

This is how I usually choose:

  • a controller's validation, status codes, JSON shape → @WebMvcTest, with the service mocked;
  • complex JPQL, native queries, mapping → @DataJpaTest + Testcontainers;
  • "does it all work together", transaction boundaries, the security chain → a few @SpringBootTests.

A common mistake: putting @SpringBootTest on every test and then mocking half the beans inside. The tests end up slow and still don't check the real integration.

One more nuance: by default @SpringBootTest doesn't start a real server (webEnvironment = MOCK). If you need a real port, use RANDOM_PORT.