- Understand Spring Boot's test slice annotations
- Learn how to test REST controllers with
@WebMvcTest - Get comfortable with MockMvc for simulating HTTP requests
- Use
@MockitoBeanto replace real beans with mocks in a test slice - Test security-protected endpoints with
@WithMockUser
- Spring Boot test slices load only the required components for testing specific layers
- Use
@MockitoBeanto replace real beans with mocks in a test slice @WebMvcTestloads only web-related components (controllers, filters, etc.)- Use MockMvc to simulate HTTP requests without starting a server
- Include
@Import(SecurityConfig.class)if you need to test with security enabled
In this exercise, you'll use @WebMvcTest to test the BookController in isolation from the rest of the application.
Tasks:
- Open
Exercise1WebMvcTest.javain theexercisespackage - Implement test methods to verify controller behavior
- Use
MockMvcto simulate HTTP requests and verify responses - Mock the
BookServiceto return predetermined data
Tips:
- Use
@MockitoBeanto replace the real BookService with a mock - Configure mock behavior with Mockito's when/thenReturn
- Use MockMvc's
perform()method to simulate HTTP requests - Include the Spring Security config with
@Import(SecurityConfig.class) - Use
andExpect()to validate the response - Check the solution in
Solution1WebMvcTest.java