AssertJ例外アサーション
1概要
このクイックチュートリアルでは、http://joel-costigliola.github.io/assertj/[AssertJ]の例外専用アサーションを見ていきます。
2. AssertJなし
例外がスローされたかどうかをテストするには、例外をキャッチしてからアサーションを実行する必要があります。
try {
//...
} catch (Exception e) {
//assertions
}
しかし、例外がスローされない場合はどうなりますか。その場合、テストは成功します。テストケースを手動で失敗させる必要があるのはこのためです。
3 AssertJ
とは
Java 8を使用すると、AssertJとλの式を利用することで、例外に関するアサーションを簡単に実行できます。
3.1.
assertThatThrownBy()
を使用する
リスト内の範囲外の項目にインデックスを付けると、__IndexOutOfBoundsExceptionが発生するかどうかを確認しましょう。
assertThatThrownBy(() -> {
List<String> list = Arrays.asList("String one", "String two"));
list(2);
}).isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageContaining("Index: 2, Size: 2");
例外をスローする可能性のあるコードフラグメントがラムダ式としてどのように渡されるかに注意してください。
もちろん、ここではさまざまな標準のAssertJアサーションを活用できます。
.hasMessage("Index: %s, Size: %s", 2, 2)
.hasMessageStartingWith("Index: 2")
.hasMessageContaining("2")
.hasMessageEndingWith("Size: 2")
.hasMessageMatching("Index: \\d+, Size: \\d+")
.hasCauseInstanceOf(IOException.class)
.hasStackTraceContaining("java.io.IOException");
3.2.
assertThatExceptionOfType
を使用する
考え方は上の例と似ていますが、最初に例外タイプを指定できます。
assertThatExceptionOfType(IndexOutOfBoundsException.class)
.isThrownBy(() -> {
//...
}).hasMessageMatching("Index: \\d+, Size: \\d+");
3.3.
assertThatIOException
およびその他の一般的なタイプの使用
-
AssertJは以下のような一般的な例外タイプのラッパーを提供します。
assertThatIOException().isThrownBy(() -> {
//...
});
そして同様に:
-
assertThatIllegalArgumentException()
-
assertThatIllegalStateException()
-
assertThatIOException()
-
assertThatNullPointerException()
3.4. アサーションからの例外の分離
私たちのユニットテストを書くもう一つの方法は
別々のセクションに
when
と
then
ロジックを書くことです:
----//when
Throwable thrown = catchThrowable(() -> {
//...
});
//then
assertThat(thrown)
.isInstanceOf(ArithmeticException.class)
.hasMessageContaining("/by zero");
----
4結論
そして我々はそこにいます。この短い記事では、** 例外に対してアサーションを実行するためにAssertJを使用するさまざまな方法について説明しました。
いつものように、この記事に関連するコードはhttps://github.com/eugenp/tutorials/tree/master/testing-modules/testing[Githubで利用可能]です。