21. import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
// ... 생략
assertThat(fellowshipOfTheRing).hasSize(9);
// 일반적으로 예외 발생에 대한 검증 처리
try {
fellowshipOfTheRing.get(9); // 예외 발생!!!
// 여기까지 코드가 오는 것은 기대했던 예외가 발생하지 않았다는 뜻! 검증 실패
fail("IndexOutOfBoundsException expected because fellowshipOfTheRing has only 9 elements");
} catch (IndexOutOfBoundsException e) {
assertThat(e).hasMessage("Index: 9, Size: 9");
}
// 주의점 : Throwable 로 catch 하면 안된다.
// 그러면 fail로 발생한 AssertionError 도 catch 해서 검증 성공으로 인식해 버린다.
// 다른 방식
try {
fellowshipOfTheRing.get(9); // 예외 발생!!
// 기대했던 예외가 발생하지 않았다는 뜻! 검증 실패
failBecauseExceptionWasNotThrown(IndexOutOfBoundsException.class);
} catch (IndexOutOfBoundsException e) {
assertThat(e).hasMessage("Index: 9, Size: 9");
}
With Java 7
22. @Test
public void testException() {
assertThatThrownBy(() -> { throw new Exception("boom!")
}).isInstanceOf(Exception.class)
.hasMessageContaining("boom");
}
With Java 8
@Test
public void testException() {
// given some preconditions
// …
// when
Throwable thrown = catchThrowable(() -> { throw new Exception("boom!") });
// then
assertThat(thrown).isInstanceOf(Exception.class) .hasMessageContaining("boom");
}
With Java 8 BDD
23. // 두 인스턴스가 같은 배우이고, 속성 중 종족 값만 같은 경우...
// fredo 와 sam 은 다른 사람이지만 같은 호빗족이다.
assertThat(frodo).isNotEqualTo(sam);
// raceComparator 가 Comparator<AClass> 이면서 race 값만 비교하는 경우
assertThat(frodo).usingComparator(raceComparator).isEqualTo(sam);
// 절대반지 그룹에 간달프는 속해있지만, 사우론은 아니다
assertThat(fellowshipOfTheRing).contains(gandalf).doesNotContain(sauron);
// 하지만 종족을 비교하는 raceComparator 를 사용하면 사우론도 간달프와 같은 Maia 종족이다.
assertThat(fellowshipOfTheRing)
.usingElementComparator(raceComparator)
.contains(sauron);
usingElementComparator(Comparator) example:
usingComparator(Comparator) example: