0Pricing
Java Academy · Lesson

Spring Boot Test Slices: @WebMvcTest and @DataJpaTest

Use @WebMvcTest to test controllers in isolation and @DataJpaTest for repository layer testing.

What Are Test Slices?

Test slices load only the relevant portion of the Spring context for a specific layer. They are faster than @SpringBootTest (which loads everything) and isolate the layer under test.

@WebMvcTest: Controller Layer Only

@WebMvcTest(UserController.class) loads only the web layer: controllers, filters, security config, and Jackson. Services and repositories must be mocked with @MockBean.

@WebMvcTest(UserController.class)
class UserControllerTest {
    @Autowired MockMvc mockMvc;
    @MockBean UserService userService;
    @Test
    void get_user_returns_200() throws Exception {
        given(userService.findById(1L)).willReturn(new UserDto(1L, "Alice"));
        mockMvc.perform(get("/api/users/1"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.name").value("Alice"));
    }
}

All lessons in this course

  1. Parameterized Tests with @CsvSource and @MethodSource
  2. Mockito Advanced: Argument Captors and Spies
  3. Spring Boot Test Slices: @WebMvcTest and @DataJpaTest
  4. Testcontainers: Real Database Integration Tests
← Back to Java Academy