JVM

BDDMockito

kyoulho 2024. 7. 28. 13:28

BDDMockito는 Behavior-Driven Development (BDD) 스타일의 단위 테스트를 작성하기 위해 Mockito 프레임워크를 확장한 것이다. BDDMockito는 주로 Java 애플리케이션에서 사용되며, 테스트 코드가 더 읽기 쉽고 명확하게 작성되도록 도와준다.

BDDMockito의 장점

  1. 가독성 향상: BDD 스타일의 테스트는 테스트 코드의 가독성을 높여, 테스트 목적을 더 명확하게 표현할 수 있다.
  2. 행동 중심: Given-When-Then 패턴을 통해, 테스트 케이스를 시스템의 동작과 일치시킬 수 있다.
  3. 명확한 의도 표현: BDD 스타일의 테스트는 코드의 의도를 더 명확하게 표현하여, 테스트 케이스를 이해하고 유지보수하기 쉽게 만든다.

BDDMockito의 주요 메서드

  1. given: 테스트 준비 단계에서 사용되며, when의 BDD 버전
  2. willReturn: 특정 조건에서 메서드 호출에 대해 반환할 값을 설정
  3. willThrow: 특정 조건에서 예외를 던지도록 설정
  4. willAnswer: 특정 조건에서 사용자 정의 동작을 설정
  5. willDoNothing: 아무런 동작도 하지 않도록 설정
  6. willCallRealMethod: 실제 메서드를 호출하도록 설정

기본적인 사용법

import static org.mockito.BDDMockito.*;

import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(MockitoExtension.class)
public class SomeServiceTests {

    @Mock
    private SomeRepository repository;

    @InjectMocks
    private SomeService service;

    @Test
    void testFindById() {
        // Given
        SomeEntity entity = new SomeEntity();
        given(repository.findById(1L)).willReturn(Optional.of(entity));

        // When
        SomeEntity result = service.findById(1L).orElse(null);

        // Then
        assertNotNull(result);
        then(repository).should().findById(1L);
    }
}

예외를 던지는 경우

import static org.mockito.BDDMockito.*;

import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(MockitoExtension.class)
public class SomeServiceTests {

    @Mock
    private SomeRepository repository;

    @InjectMocks
    private SomeService service;

    @Test
    void testFindByIdThrowsException() {
        // Given
        given(repository.findById(1L)).willThrow(new RuntimeException("DB Error"));

        // When/Then
        assertThrows(RuntimeException.class, () -> service.findById(1L));
        then(repository).should().findById(1L);
    }
}

사용자 정의 동작 설정

import static org.mockito.BDDMockito.*;

import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(MockitoExtension.class)
public class SomeServiceTests {

    @Mock
    private SomeRepository repository;

    @InjectMocks
    private SomeService service;

    @Test
    void testFindByIdWithCustomAnswer() {
        // Given
        given(repository.findById(1L)).willAnswer(invocation -> {
            Long id = invocation.getArgument(0);
            return Optional.of(new SomeEntity(id));
        });

        // When
        SomeEntity result = service.findById(1L).orElse(null);

        // Then
        assertNotNull(result);
        assertEquals(1L, result.getId());
        then(repository).should().findById(1L);
    }
}

 

'JVM' 카테고리의 다른 글

Jackson의 ObjectMapper: 객체 생성 방식과 필드 바인딩  (0) 2024.08.10
MockServer  (0) 2024.07.29
JUnit  (0) 2024.07.28
테스트 커버리지와 JaCoCo  (0) 2024.07.27
StringBuffer vs StringBuilder  (0) 2024.07.22