[java] Mockito와 MockMvc를 사용한 통합 테스트

Mockito와 MockMvc는 자바 애플리케이션의 단위 및 통합 테스트에서 매우 유용한 도구입니다. 이 블로그 포스트에서는 Mockito와 MockMvc를 사용하여 스프링 부트 애플리케이션의 통합 테스트를 작성하는 방법에 대해 알아보겠습니다.

Mockito

Mockito는 자바에서 모의 객체(Mocking Object)를 생성하고 제공하는 라이브러리입니다. 이를 사용하면 외부 의존성을 모의(mock)로 대체하여 코드의 단위 테스트가 용이해집니다. Mockito를 사용하면 외부 서비스나 데이터베이스에 의존하지 않고도 코드를 테스트할 수 있습니다.

다음은 Mockito를 사용하여 간단한 모의 객체를 생성하는 예제입니다.

import static org.mockito.Mockito.*;

// 테스트 대상 클래스
public class UserService {
    private UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public boolean deleteUser(Long userId) {
        if (userRepository.existsById(userId)) {
            userRepository.deleteById(userId);
            return true;
        }
        return false;
    }
}

// 테스트 코드
public class UserServiceTest {
    @Test
    public void testDeleteUser() {
        UserRepository userRepository = mock(UserRepository.class);
        when(userRepository.existsById(1L)).thenReturn(true);

        UserService userService = new UserService(userRepository);
        boolean result = userService.deleteUser(1L);

        assertTrue(result);
        verify(userRepository, times(1)).deleteById(1L);
    }
}

이 예제에서는 UserService 클래스의 deleteUser 메서드를 테스트하는데, UserRepository 인터페이스를 모의 객체로 대체하여 외부 의존성을 제어합니다.

MockMvc

MockMvc는 스프링 애플리케이션의 HTTP 요청을 모의(mock)하고 검증하는 데 사용되는 테스트 도구입니다. 이를 사용하면 컨트롤러의 동작을 모의하고 테스트할 수 있으며, 실제 HTTP 요청을 보내지 않고도 컨트롤러를 테스트할 수 있습니다.

다음은 MockMvc를 사용하여 스프링 부트 애플리케이션의 통합 테스트를 작성하는 예제입니다.

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerIntegrationTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    public void testGetUserById() throws Exception {
        User user = new User(1L, "John Doe");
        when(userService.getUserById(1L)).thenReturn(user);
        
        mockMvc.perform(get("/users/{id}", 1L))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.id", is(1)))
            .andExpect(jsonPath("$.name", is("John Doe")));
    }
}

이 예제에서는 UserControllerIntegrationTest 클래스에서 MockMvc를 사용하여 UserController 클래스를 테스트하고 있습니다.

Mockito와 MockMvc는 각각 단위 및 통합 테스트에 유용한 도구로서, 자바 애플리케이션의 품질을 향상시키는 데 큰 도움이 됩니다.

참조: