Controller Testing

Sungju Kim·2024년 12월 18일

Initial Set Up

public class UserControllerTest {
    @Mock
    private UserService userService;
    
    @Mock
    private JwtUtil jwtUtil;

    @InjectMocks
    private UserController userController;
    
    private MockMvc mockMvc;

    private ObjectMapper objectMapper;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
        objectMapper = new ObjectMapper();
    }

}

Explanation

ObjectMapper

  • ObjectMapper is a utility class from the Jackson library.
  • It is used to serialize Java objects into JSON and deserialize JSON into Java objects.
  • It simplifies converting Java objects into JSON strings when testing APIs.
  • It ensures consistent JSON formatting, similar to how a real API would process input/output.

Example Usage:

Suppose you need to send a UserRequestDto object in your test:

UserRequestDto request = new UserRequestDto("John", "john@example.com");
String jsonRequest = objectMapper.writeValueAsString(request);

You can then use this jsonRequest as the body of an HTTP request in your test.

MockMvc

  • MockMvc is part of the Spring Test framework.
  • It helps validate the behavior of your controller methods, such as response status, headers, and body.
  • It mocks the entire HTTP request/response lifecycle, providing a lightweight and fast way to test your REST APIs without starting a full web server.

Example Usage:

To test a POST API:

mockMvc.perform(post("/api/users")
        .contentType(MediaType.APPLICATION_JSON)
        .content(jsonRequest))
    .andExpect(status().isOk())
    .andExpect(jsonPath("$.message").value("User created successfully"));

This performs a POST request to the /api/users endpoint with a JSON payload and checks:
1. The response HTTP status is 200 OK.
2. The message field in the JSON response equals "User created successfully".

profile
Fully ✨committed✨ developer, always eager to learn!

0개의 댓글