본문 바로가기

Web/spring

[Spring JUnit5 Test] 간단한 코드 작성

728x90
@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/{userId}")
    public UserDto getUserById(@PathVariable Long userId) {
        return userService.getUserById(userId);
    }

    @PostMapping
    public UserDto createUser(@RequestBody CreateUserDto createUserDto) {
        return userService.createUser(createUserDto);
    }

    @PutMapping("/{userId}")
    public UserDto updateUser(@PathVariable Long userId, @RequestBody UpdateUserDto updateUserDto) {
        return userService.updateUser(userId, updateUserDto);
    }

    @DeleteMapping("/{userId}")
    public void deleteUser(@PathVariable Long userId) {
        userService.deleteUser(userId);
    }
}

 

 

 

테스트 코드 작성

 

@ExtendWith(MockitoExtension.class)
class UserControllerTest {

    @Mock
    private UserService userService;

    @InjectMocks
    private UserController userController;

    private MockMvc mockMvc;

    @BeforeEach
    void setUp() {
        mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
    }

    @Test
    void testGetUserById() throws Exception {
        // given
        Long userId = 1L;
        UserDto userDto = new UserDto(userId, "john@example.com", "John", "Doe");
        given(userService.getUserById(userId)).willReturn(userDto);

        // when
        MvcResult result = mockMvc.perform(get("/api/users/{userId}", userId))
                .andExpect(status().isOk())
                .andReturn();

        // then
        String responseBody = result.getResponse().getContentAsString();
        assertThat(responseBody).isEqualTo(objectMapper.writeValueAsString(userDto));
    }

    @Test
    void testCreateUser() throws Exception {
        // given
        CreateUserDto createUserDto = new CreateUserDto("john@example.com", "John", "Doe");
        UserDto userDto = new UserDto(1L, "john@example.com", "John", "Doe");
        given(userService.createUser(createUserDto)).willReturn(userDto);

        // when
        MvcResult result = mockMvc.perform(post("/api/users")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(createUserDto)))
                .andExpect(status().isOk())
                .andReturn();

        // then
        String responseBody = result.getResponse().getContentAsString();
        assertThat(responseBody).isEqualTo(objectMapper.writeValueAsString(userDto));
    }

    @Test
    void testUpdateUser() throws Exception {
        // given
        Long userId = 1L;
        UpdateUserDto updateUserDto = new UpdateUserDto("john@example.com", "John", "Doe");
        UserDto userDto = new UserDto(userId, "john@example.com", "John", "Doe");
        given(userService.updateUser(userId, updateUserDto)).willReturn(userDto);

        // when
        MvcResult result = mockMvc.perform(put("/api/users/{userId}", userId)
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(updateUserDto)))
                .andExpect(status().isOk())
                .andReturn();

        // then
        String responseBody = result.getResponse().getContentAsString();
        assertThat(responseBody).isEqualTo(objectMapper.writeValueAsString(userDto));
    }
	@Test
    void testDeleteUser() throws Exception {
        // given
        Long userId = 1L;
        User user = new User(userId, "test", "test");
        given(userService.getUserById(userId)).willReturn(user);

        // when
        mockMvc.perform(delete("/users/{id}", userId))

        // then
            .andExpect(status().isOk())
            .andExpect(content().string("User with ID: " + userId + " has been deleted"));
        verify(userService, times(1)).deleteUserById(userId);
	}

}

 

728x90