Test

Mock, InjectMocks 어노테이션

devkimc 2023. 9. 23. 21:42

@Mock란

단위테스트 시, 모의 클래스를 만들 때 사용합니다.

서비스나 컨트롤러 단위 테스트를 할때 여러 제한적인 상황이 있습니다.
레포지토리와 의존성을 어떻게 해결할지, DB연동을 하지 않고 어떻게 분리해서 테스트를 할지 고민을 하게 됩니다.


이럴 때 편리함을 주는 어노테이션이 @Mock입니다.

    @Test
    @DisplayName("가장 많이 저장된 맛집 조회")
    public void get_fav_rests_ranking_most_save() throws Exception {

        RestRepository restRepository = Mockito.mock(RestRepository.class);
        RankingRestaurantService rankingRestaurantService = new RankingRestaurantServiceImpl(restRepository);

@Mock을 사용하지 않으면 위처럼 Mockito.mock() 을 사용하여 Mock 객체를 생성하고 의존성을 해결해야 합니다.

 

    @Mock 
    private RestRepository restRepository;

    @Test
    @DisplayName("가장 많이 저장된 맛집 조회")
    public void get_fav_rests_ranking_most_save() throws Exception {

        RankingRestaurantService rankingRestaurantService = new RankingRestaurantServiceImpl(restRepository);

@Mock은 Mock 객체 생성을 쉽게 할 수 있도록 도와줍니다.

 

@InjectMocks란

@InjectMocks는 Mock 객체를 원하는 클래스에 의존성 주입하고 싶을 때 사용합니다.
@InjectMocks는 해당 클래스(rankingService)가 필요한 의존성과 맞는 Mock 객체들(restRepository)을 감지하여 해당 클래스의 객체가 만들어질 때 사용하여 객체를 만들고 해당 변수에 객체를 주입하게 된다고 합니다.

    @Mock 
    private RestRepository restRepository;

    @InjectMocks
    private RankingRestaurantService restaurantService;

    @Test
    @DisplayName("가장 많이 저장된 맛집 조회")
    public void get_fav_rests_ranking_most_save() throws Exception {

 

참고자료

Mockito @Mock @MockBean @Spy @SpyBean 차이점