[Spring] mockito 이용한 Entity 테스트 코드

hyewon jeong·2023년 3월 11일
0

Spring

목록 보기
40/59

예외가 발생하지 않는 경우

assertThatNoException()

public class TestPlayGround {
	@Test
	public void Test_1() {
		assertThatNoException().isThrownBy(() -> System.out.println("OK"));
	}
}

에러노트. Expecting code to raise a throwable.

(1) 발생


    Long managerId1 = 1L;
    Long managerId2 = 2L;
    Notice notice = Notice.builder()
        .managerId(managerId1)
        .title("title")
        .content("content")
        .build();
    //when&then
    assertThatNoException().isThrownBy(()-> notice.isWriter(managerId1)); //예외가 발생하지 않는 경우
    assertThatThrownBy(()->notice.isWriter(managerId2)).isInstanceOf(CustomException.class);

(2) 원인

assertThatThrownBy()로 작성한 코드에, 에러가 안나서 생긴 문제였다.

(3) 해결

assertThatThrownBy() 대신, assertThatCode() 를 사용하자.
assertThatThrownBy()는 예외가 던져지지 않으면 바로 실패하고, 에러메세지도 나타나지 않지만,
assertThatCode()는 예외가 던져지지 않아도 실패하지 않고, 에러 메세지도 뜨기 때문에 고치기 쉽다.

참고
AssertJ 의 Exception 처리

profile
개발자꿈나무

0개의 댓글