Testing: @SpringBootTest vs @WebMvcTest vs @DataJpaTest

Difficulty: Intermediate

Question

What are the different Spring Boot test annotations, and when should you use @SpringBootTest versus a test slice like @WebMvcTest?

Answer

A common mistake in early projects is annotating every test with @SpringBootTest. It works, but each test then starts the entire application context, including the database, security, and every bean, and the suite takes ten minutes. Spring Boot provides test slices to load only the part of the application you are testing, making tests faster and more focused. Choosing the right level is the skill being tested here.

Think of the testing pyramid. At the bottom are plain unit tests with JUnit 5 and Mockito, no Spring at all. You instantiate a service with mock dependencies through its constructor and test the logic in milliseconds. This is the majority of your tests, and it is another reason constructor injection matters. In the middle are slice tests. At the top are a few full integration tests.

@WebMvcTest(StudentController.class) loads only the web layer: the controller, controller advice, Jackson configuration, filters, and MockMvc. It does not load services or repositories, so you provide them as mocks using @MockBean, or @MockitoBean in newer Boot versions. You use it to verify URL mapping, request parsing, validation, status codes, JSON output, and error handling. @DataJpaTest loads only JPA components: entities, repositories, and an embedded database by default, wrapped in a transaction that rolls back after each test. It is ideal for checking derived queries and custom @Query methods; add @AutoConfigureTestDatabase(replace = NONE) plus Testcontainers when you want to test against a real PostgreSQL or MySQL, because H2 can behave differently. There are further slices like @JsonTest for serialisation, @DataMongoTest, and @RestClientTest.

@SpringBootTest loads the complete context. Use it for end-to-end flows, where several layers interact, for example controller through service to repository and database. With webEnvironment = RANDOM_PORT it starts a real embedded server, and you call it with TestRestTemplate or WebTestClient. With the default MOCK environment it uses MockMvc via @AutoConfigureMockMvc. Keep these tests few because they are slow, and share the cached context across tests by avoiding unnecessary @MockBean variations, since each different set of mocks creates a new context.

Related points to mention: @ActiveProfiles("test") selects test properties, @TestPropertySource overrides values, and @Sql seeds data. @DirtiesContext discards the cached context, but use it sparingly since it is expensive. Testcontainers gives a disposable real database or Kafka broker in Docker, and Boot 3.1 added @ServiceConnection to wire it automatically.

The take-away for your answer: unit test business logic with Mockito, slice test each layer for behaviour that depends on Spring, and keep a thin layer of full integration tests for critical paths. This gives fast feedback and real confidence together.

Code examples

Three test levels

// 1. Plain unit test: no Spring
class StudentServiceTest {
    private final StudentRepository repo = mock(StudentRepository.class);
    private final StudentService service = new StudentService(repo);

    @Test
    void throwsWhenMissing() {
        when(repo.findById(9L)).thenReturn(Optional.empty());
        assertThrows(StudentNotFoundException.class, () -> service.find(9L));
    }
}

// 2. Web slice: only controller + advice
@WebMvcTest(StudentController.class)
class StudentControllerTest {
    @Autowired MockMvc mvc;
    @MockBean StudentService service;

    @Test
    void returnsStudent() throws Exception {
        when(service.find(1L)).thenReturn(new StudentDto(1L, "Asha"));
        mvc.perform(get("/api/students/1"))
           .andExpect(status().isOk())
           .andExpect(jsonPath("$.name").value("Asha"));
    }
}

// 3. Repository slice
@DataJpaTest
class StudentRepositoryTest {
    @Autowired StudentRepository repo;

    @Test
    void findsByEmail() {
        repo.save(new Student("Asha", "asha@x.com"));
        assertTrue(repo.findByEmail("asha@x.com").isPresent());
    }
}

Each test loads exactly what it needs; the unit test needs no Spring context at all.

Key points

Common follow-up questions

Interview tips

Concepts covered

SpringBootTest, WebMvcTest, DataJpaTest, Test Slices

More Spring Boot questions