본문 바로가기
Spring/junit5 테스트

[스프링부트] junit 테스트 코드(5/5) - 예외 테스트

by 옹알이옹 2023. 8. 8.

 1. 예외 테스트란

실제 코드를 작성할 때 개발자는 예외처리를 하게 된다. 그에 따라 테스트코드를 작성할 때 예외 처리가
개발자가 의도한대로 동작하는지에 대해서도 테스트 코드를 통한 검증이 필요하다.

 2. 예외 테스트 작성 방법

 

Service코드

/**
 * 게시판 생성
 * @param boardCreateDto
 */
public Board createBoard(BoardCreateDto boardCreateDto) {

    // memberNo를 통해 회원 엔티티 조회 => 조회 결과가 없다면 예외
    Member findMember = memberRepository.findById(boardCreateDto.getMemberNo()).orElseThrow(() -> new ResourceNotFoundException("Member","memberNo",boardCreateDto.getMemberNo()));

    // Board와 Member 연관 관계 세팅
    boardCreateDto.setMember(findMember);

    // DTO -> Entity 변환
    Board board = boardCreateDto.toEntity();

    Board save = null;

    // boardNm이 중복된다면 예외
    if(boardRepository.existsByBoardNm(boardCreateDto.getBoardNm()))
        throw new ResourceDuplicateException("Board", "boardNm", boardCreateDto.getBoardNm());

    try {
        save = boardRepository.save(board);
    } catch (DataAccessException e) {
        throw new CustomSqlException();
    }

    return save;
}
위의 service 코드를 보면 두 가지 상황에 대해 예외 발생 상황을 예측하여 GlobalException 처리를 진행하였다.
1. 게시판 생성시 회원 객체의 정보가 필요한데, 실제 memberNo를 통해 조회한 회원이 없을 때 발생
2. boardNm에 유니크 제약 조건이 걸려 있어 중복된 값을 저장할 때 DB에서 에러가 발생하게 된다.
   그러하여 service단에서 미리 boardNm으로 조회를하여 존재한다면 예외를 발생 시킨다.
현재 ResourceNotFoundException, ResourceDuplicateException 두 가지의 커스텀 예외 클래스를 만들어 GlobalExceptionHandler에 등록해 사용 중이다.

 

1. 조회한 회원이 없을 경우

@Test
@Order(2)
@DisplayName("게시판 등록 실패(등록자 조회 실패) - 통합 테스트")
void notFoundUser() throws Exception {

    // given
    BoardCreateDto boardCreateDto = BoardCreateDto.builder()
            .boardNm("통테")
            .memberNo(999L)
            .build();
    String param = objectMapper.writeValueAsString(boardCreateDto);

    // when
    ResultActions resultActions = mockMvc.perform(post("/board")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(param));
    // then
    resultActions
            .andExpect(status().is4xxClientError())
            .andDo(result -> {

        // 실제 테스트 중 발생한 예외
        Exception resolvedException = result.getResolvedException();

        assertTrue(resolvedException instanceof ResourceNotFoundException);
    });
}
  • 현재 DB에 존재하지 않는 memberNo를 파라미터로 전달
  • 위에서 구현해놓은 service 로직을 통해 ResourceNotFoundException 발생
  • mockMvc를 통해 요청을 날린 뒤 해당 결과가 담긴 ResultActions 객체를 통해 실제 발생한 예외를 조회한다.
  • 요청에 대한 응답 코드가 404인지 검증한다.
  • 조회한 예외 클래스와 예상한 예외 클래스가 동일한지 검증한다.
반응형