본문 바로가기
Project/Web | Server

Point API - TDD 개발하기

by 코젼 2024. 6. 18.
728x90
반응형

Github https://github.com/kdelay/Point-API-TDD

API 개발하면서 배운 점 작성하기

 

GitHub - kdelay/Point-API-TDD: 💠 포인트 충전, 조회 등 관련 API - TDD 작성하기 💠

💠 포인트 충전, 조회 등 관련 API - TDD 작성하기 💠. Contribute to kdelay/Point-API-TDD development by creating an account on GitHub.

github.com

목차


질문 메모

  • Controller 유저 id 유무에 따라서만 테스트 하면 되는지?

 

Controller 테스트

  • controller 테스트는 http 계층을 다루기 때문에 integration test이다.
  • 스프링에서 통합 테스트는 필요한 모든 빈을 포함하고 있는 Application Context를 실행한다.
    • 특정 url 수신, 예외 반환 역할 bean 등 포함

1. controller가 해당 ur을 잘 listen 하는지 확인

- verifying http request matching

2. input이 원하는 java object로 serialization 되는지 확인

- verifying input deserializtion

3. input validation check 동작 확인

- verifying input validation

4. 예상한대로 비즈니스 로직이 불렸는지 확인

- verifying business logic calls

5. http 응답 본문에 json 형태의 유효한 값이 포함되어있는지 확인

- verifying output serialization

6. 예외 처리

- verifying exception handling

 

Service 테스트

단위 테스트를 위해 mock을 이용한다.

MockitoAnnotations.openMocks(this): @Mock, @Spy, @InjectMocks 필드 초기화 및 모의 객체 주입

@InjectMocks
private PointService pointService;

@Mock
private UserPointTable userPointTable;

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

테스트 유저 추가

@BeforeEach
void setUp() {
    //모의 객체 초기화
    mocks = MockitoAnnotations.openMocks(this);

    //테스트 유저 추가
    when(userPointTable.selectById(1L)).thenReturn(new UserPoint(1L, 50L, System.currentTimeMillis()));
    when(userPointTable.selectById(2L)).thenReturn(UserPoint.empty(2L));
    when(userPointTable.insertOrUpdate(anyLong(), anyLong())).thenAnswer(invocation -> {
        long id = invocation.getArgument(0);
        long amount = invocation.getArgument(1);
        return new UserPoint(id, amount, System.currentTimeMillis());
    });

    //아이디 유효성 테스트
    isEmptyId();
    isInvalidId();
}

Issue

'AutoCloseable' used without 'try'-with-resources statement

해결 방법
try-with-resources 문을 사용하여 openMocks를 호출하고, 테스트가 완료된 후에 자동으로 자원을 닫을 수 있습니다.

 

MockitoAnnotations.openMocks(this);가 AutoCloseable을 구현하고 있기 때문에 발생합니다.

이를 해결하기 위해 try-with-resources 문을 사용해야 합니다.

try-with-resources 문을 사용하면 자원을 자동으로 닫아주므로 더 안전한 코드를 작성할 수 있습니다.

private AutoCloseable mocks;

@BeforeEach
void setUp() {
    //모의 객체 초기화
    mocks = MockitoAnnotations.openMocks(this);
}

@AfterEach
void tearDown() throws Exception {
    // 테스트가 끝난 후 자원 해제
    mocks.close(); 
}​

 


Annotation

@MockBean vs @Mock

@MockBean
  • 주입된 빈을 테스트에서 Mock 객체로 대체할 수 있도록 한다.
  • 실제 구현체 대신에 Mock 객체를 사용해서 의존성을 관리할 수 있다. 테스트의 격리성을 확보하고, 외부 요소에 의존하지 않고 테스트를 진행할 수 있다.
  • 테스트 의존성을 관리하고, 외부 환경에 독립적으로 테스트를 진행할 수 있게 해준다.
요약

@Mock: Mockito 라이브러리에서 제공하는 목 객체 생성용 애노테이션. 단위 테스트에서 사용.

@MockBean: 스프링 테스트에서 사용되며, 스프링 애플리케이션 컨텍스트에서 실제 빈을 대체하는 목적으로 사용됨. 스프링의 @Autowired와 함께 사용됨.

@InjectsMock

  • Mockito 라이브러리 제공 애노테이션
  • 테스트 대상이 되는 클래스의 인스턴스를 생성할 때 의존하는 다른 객체들을 자동으로 주입할 때 유용하게 활용된다
728x90
반응형

'Project > Web | Server' 카테고리의 다른 글

사내 출퇴근 프로그램 API 개발  (0) 2024.06.08
나만의 웹 페이지 만들기  (0) 2022.07.13

댓글