LoginSignup
1
0

JUnit5のasserThrowsを使おう

Last updated at Posted at 2024-04-10

JUnit5のasserThrows

kotlinでサーバサイドアプリ開発していますが、今までJUnitでテスト対象の関数が例外をthrowするような場合、こんな風に書いていました。
また、JUnit4でも、このような書き方になると思います。

try {
    hogehogeFunc()
    fail("例外がthrowされませんでした")
} catch (e: Exception) {
    when (e) {
        // assert
        is MyException -> assertThat(e.message).isEqualTo("エラーメッセージ")
        else -> {
            e.printStackTrace()
            fail("throwされた例外が異なります")
        }
    }
}

JUnit5のドキュメントを見ていたら、assertThrowsなるものがあるのを発見!
これだと

val err = assertThrows<MyException> { hogehogeFunc() }
assertThat(err.message).isEqualTo("エラーメッセージ")

たったこれだけです。
期待通りの例外がthrowsされればテストは成功します。

期待したのと違う例外がthrowsされた場合は

予想:class foo.IOException
実際:class java.lang.IllegalArgumentException
IO Errororg.opentest4j.AssertionFailedError: Unexpected exception type thrown, expected: <foo.MyException> but was: <java.lang.IllegalArgumentException>
	at org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:151)
	at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:67)
	at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:35)
	at org.junit.jupiter.api.Assertions.assertThrows(Assertions.java:3115)

となります。

期待した例外がthrowsされなかった場合は

Expected foo.MyException to be thrown, but nothing was thrown.
org.opentest4j.AssertionFailedError: Expected foo.MyException to be thrown, but nothing was thrown.

となります。

随分、簡潔に書けますね。これからはこの書き方で書こうと思います。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0