[JUnit5] ExpectedException Rule

Jiwoo Kim·2021년 3월 25일
0

단위테스트와 JUnit

목록 보기
3/9
post-thumbnail

3장 | JUnit 단언 깊게 파기

Exception

예외를 발생시키고 단언하는 방법에 대해 정리했다.

Test Annotation

  • @Test(expected=SomeException.class)
  • 예외 발생하지 않으면 java.lang.AssertionError 발생하고 test fail

위 annotation만으로는 발생한 예외의 구체적인 상태를 확인하기 번거롭다.
따라서 우리는 ExpectedException@Rule을 활용하여 구체적으로 예외를 테스트 해야 한다.

ExpectedException Rule

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void exceptionRule() {
	thrown.expect(InsufficientFundsException.class);
	thrown.expectMessage("balance only 0");
	account.withdraw(100);
}
  • test 셋업 단계에서 나머지 테스트를 실행할 때 발생할 수 있는 일을 rule에 명시
  • rule 기대사항을 예외 객체가 모두 만족시키지 못하면 test fail

0개의 댓글