Controller Layer Unit Testing Flashcards
MockMvc
MockMvc is a Spring MVC test framework that allows you to perform HTTP requests and assert the results. Provides methods to simulate GET, POST, PUT, DELETE, and other HTTP methods. Useful for testing request and response handling in the controller.
@WebMvcTest
used for testing the controller layer in isolation. Loads only the specified controller and its related components, not the entire application context.
@MockBean
@MockBean used in conjunction with @WebMvcTest to create and inject mock instances of dependencies (e.g., services) into the controller.
Example
@WebMvcTest(UserController.class)
public class UserControllerTests {
@Autowired private MockMvc mockMvc; @MockBean private UserService userService; @Test public void registerUserSuccess() throws Exception { // Prepare a valid UserDto request body String userDtoJson = "{\"name\": \"Test\", \"email\": \"test@gmail.com\"}"; // Mock userService.registerUser to return a successful response when(userService.registerUser(any())).thenReturn(ResponseEntity.status(HttpStatus.CREATED).body("Success: User details successfully saved!")); // Perform POST request to /user/new with valid UserDto mockMvc.perform(MockMvcRequestBuilders.post("/user/new") .contentType(MediaType.APPLICATION_JSON) .content(userDtoJson)) // Verify that the response status code is 201 create. .andExpect(MockMvcResultMatchers.status().isCreated()) .andExpect(MockMvcResultMatchers.content().string("Success: User details successfully saved!")); }
@MockBean vs @Mock
@MockBean Replaces a bean in the Spring Application Context with a mock, so that the mock is injected anywhere the bean is used.
Provided by: Spring Boot’s spring-boot-test module.
@Mock
reates a mock instance without adding it to the Spring Application Context.
Provided by: Mockito