Skip to main content
PreparationZone Logo
PrepZone

@WebMvcTest, @DataJpaTest, MockMvc

Testing layers in isolation with slice annotations and MockMvc.

Pass checkpoint below

Why this matters

  • Full @SpringBootTest loads every bean, every auto-configuration, and every external client — a suite of two hundred integration tests can take minutes.
  • @WebMvcTest loads just the web layer; you verify HTTP status codes, JSON shapes, and validation without a database.
  • @DataJpaTest loads JPA and an in-memory database; you verify query methods and entity mappings in isolation.

Slice tests

L1 · Fresher

@WebMvcTest loads only MVC slices; @DataJpaTest loads JPA with an in-memory DB — faster than full context.

MockMvc

L2 · Intermediate

Call endpoints without a real server; assert status, JSON body, and headers for BookStore controllers.

@MockBean

L3 · Advanced

Replace collaborators in the slice context — distinguish @Mock (JUnit) from @MockBean (Spring test context).

Test pyramid

L4 · Expert

Many fast slice/unit tests, fewer full integration tests — slice tests catch mapping bugs cheaply.

Servlet FilterEncoding, CORS
Security Filter ChainAuth, CSRF
DispatcherServlet
HandlerInterceptorPre/post handle
Controller
Filters run before DispatcherServlet. Interceptors wrap the controller. Security filters sit in their own chain.

Test annotations and tools

  • @WebMvcTest — loads @Controller beans and MockMvc; auto-configures JSON serializers.
  • @DataJpaTest — loads @Entity classes and @Repository interfaces with an embedded database.
  • @MockBean — replaces a Spring bean with a Mockito mock inside the test context.
  • MockMvc — sends fake HTTP requests and asserts on status, headers, and response body.
  • @JsonTest — tests JSON serialization/deserialization of DTOs without any web layer.

Controller slice test

Java
// learn:fragment
@WebMvcTest(BookController.class)
class BookControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private BookService bookService;

    @Test
    void getBook_returns200WithBody() throws Exception {
        BookDetail detail = new BookDetail("978-0134685991", "Effective Java", "Joshua Bloch", 45.99);
        when(bookService.getByIsbn("978-0134685991")).thenReturn(detail);

        mockMvc.perform(get("/api/books/978-0134685991"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.title").value("Effective Java"))
                .andExpect(jsonPath("$.price").value(45.99));
    }

    @Test
    void getBook_returns404WhenMissing() throws Exception {
        when(bookService.getByIsbn("unknown"))
                .thenThrow(new BookNotFoundException("unknown"));

        mockMvc.perform(get("/api/books/unknown"))
                .andExpect(status().isNotFound())
                .andExpect(jsonPath("$.title").value("Book Not Found"));
    }
}

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 3 sections

  • Validation and request body tests
  • Repository slice test
  • Pure unit test for service logic

Test yourself

Answer these before moving on — recall is what makes it stick.