본문 바로가기
Java Spring

모키토 (Mockito) - Java Spring Test Code 기초

by Bill Lab 2024. 9. 21.
728x90

스프링 기반의 Test Code 의 대부분은

클래스를 불러와서 값을 input 해보고 의도한 결과값이 나오는지를 확인하는 것이다.

 

이때 특정 클래스를 불러와서 (상속 포함) 테스트 코드를 짜야할 경우가 생기는데,

이럴때 사용할 수 있는 라이브러리가 바로 Mockito 인 것이다.

 

Mockito 는 간단하게 mock 객체를 생성할 수 있고 mock 객체에 stub 을 정의하고,

테스트 할 수 있게 해준다.

(Mockito 를 쓰지않을 경우 직접 interface를 구현해서 테스트를 해야할 수도 있는데,

그럴 경우 작업량과 가시성이 매우 떨어지게 된다.

 

그럼 어떻게 써야하는가?

(생각보다 간단하다).

 

 

 

@Mock : 의존성 주입(모의 객체 용), 사용하지 않을 시 실제 클래스 구현채를 사용하게 되므로

                의도한 테스트 결과값을 출력할 수 없을 수 있고, 연동 오류로 인해 정확한 테스트를 할 수 없게 된다.

@Mock
private ProductFinder productFinder;

 

 

@InjectMocks: @Mock 어노테이션을 주입 

@InjectMocks
private ProductService productService;

 

 

Mock 객체를 초기화하고 필드에 할당 (전체적으로 진행)

@BeforeEach
void setUp() {
    MockitoAnnotations.openMocks(this);
}

 

 

Main Test Code

@Test
@DisplayName("상품 정보가 없으면 빈 배열을 반환")
void getProductWithEmptyList() {
    //given
    List<Product> product = List.of();

    when(productFinder.findProduct()).thenReturn(product);

    //when
    List<ProductInfo> result = productService.getProduct();

    //then
    assertThat(result).isEmpty();
}
728x90

'Java Spring' 카테고리의 다른 글

ReentrantReadWriteLock vs ReentrantLock  (1) 2024.12.21
Java 버전 관리 하기 temurin  (0) 2024.11.28
Test Code 기본 - Java Spring Boot  (0) 2024.09.18
@Builder 빌더패턴  (2) 2024.09.17
단위테스트 (unit test) - Spring Boot Test !!  (0) 2024.09.17