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();
}
}
ObjectMapper is a utility class from the Jackson library.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 is part of the Spring Test framework.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".