Controller Layer Unit Testing Flashcards

1
Q

MockMvc

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

@WebMvcTest

A

used for testing the controller layer in isolation. Loads only the specified controller and its related components, not the entire application context.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

@MockBean

A

@MockBean used in conjunction with @WebMvcTest to create and inject mock instances of dependencies (e.g., services) into the controller.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Example

A

@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!"));
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

@MockBean vs @Mock

A

@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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly