팀프로젝트

# 단위 테스트

KimMZ 2025. 2. 20. 22:45

2025.02.18 - [분류 전체보기] - #서비스 단위 테스트 코드 작성

 

사실 다양한 방법은 테스트 코드를 작성하는 것 같아서 정확하게 어떤게 보편적으로 작성하는지는 잘 모르겠다. 약간 어렵지만 반복적으로 작성해보면서 감을 익히는 게 좋을 것 같다.

사용되는 repository의 Mockito 빈을 주입해준다.
@BeforeEach는 @Test가 매번 실행되기 전 먼저 실행하게 도와주는 어노테이션이다.
 User 객체를 미리 생성해둔다. → 인증객체로 사용하기 위해 인증된 사용자 설정은
@WithMockUser(roles = "CUSTOMER")​
사용한다고 하는데 잘 이해가 안된다.
@ExtendWith(SpringExtension.class)
@DisplayName("[Payment] - 비즈니스 로직")
public class PaymentSearchServiceTest {

    private PaymentSearchService paymentSearchService;

    @MockitoBean
    private PaymentRepository paymentRepository;

    @MockitoBean
    private UserRepository userRepository;

    private UUID paymentId = UUID.randomUUID();
    private User user;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
        paymentSearchService = new PaymentSearchService(paymentRepository, userRepository);

        user = new User();
        user.setUserId(UUID.randomUUID());
        user.setRole(UserRole.CUSTOMER);
        user.setUserName("본명");
        user.setEmail("test@test.com");
        user.setPassword("1234");
        user.setNickName("test");
        user.setUserAddress("address-test");
    }
    
    # @Test 테스트코드 작성

 

예외 메시지를 비교하는 검증을 통해 테스트를 진행한다.
    @Test
    @DisplayName("결제 내역이 없는 경우, 예외를 던진다.")
    public void givenNonexistentPaymentId_whenSearchingPaymentWithPaymentId_thenThrowException() {
        // given
        paymentId = UUID.randomUUID();
        Mockito.when(paymentRepository.findById(paymentId)).thenReturn(Optional.empty());

        // when & then
        IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class, () -> {
            paymentSearchService.getPaymentById(paymentId, user); // 결제 조회 호출
        });
        // 메시지 검증
        Assertions.assertEquals("일치하는 결제 내역이 없습니다.", exception.getMessage());
    }

 

 

Mockito 객체로 결제 정보 데이터를 반환하도록 한다.

responseDto에 담아 Assertions 을 이용해서 반환한 데이터의 null이 아님을 확인하고,
 초기 조건 paymentId, orderId, userId, paymentAmount, paymentStatus 과 일치하는지 검증한다.
    @Test
    @DisplayName("결제 내역을 1건 조회할 수 있다.")
    public void givenExistingPaymentId_whenSearchingPayment_thenReturnPaymentResponseDto() {
        // given
        UUID paymentId = UUID.randomUUID();
        UUID userId = UUID.randomUUID();
        UUID orderId = UUID.randomUUID();

        // User 객체 설정
        User user = new User();
        user.setUserId(userId);
        user.setRole(UserRole.CUSTOMER);

        // Payment 객체 설정
        Payment payment = new Payment(
                paymentId,
                orderId,
                userId,
                PaymentStatus.SUCCESS,
                12900,
                LocalDateTime.now());

        // 모킹 설정
        Mockito.when(paymentRepository.findById(paymentId)).thenReturn(Optional.of(payment));
        Mockito.when(userRepository.findById(userId)).thenReturn(Optional.of(user));

        // when
        PaymentResponseDto responseDto = paymentSearchService.getPaymentById(paymentId, user);

        // then
        Assertions.assertNotNull(responseDto);
        Assertions.assertEquals(paymentId, responseDto.getPaymentId());
        Assertions.assertEquals(orderId, responseDto.getOrderId());
        Assertions.assertEquals(userId, responseDto.getUserId());
        Assertions.assertEquals(PaymentStatus.SUCCESS, responseDto.getPaymentStatus());
        Assertions.assertEquals(12900, responseDto.getPaymentAmount());
    }
}