0
0

More than 1 year has passed since last update.

Kotlin&AssertJでsuspendな関数をテストする時に気をつけること

Last updated at Posted at 2022-12-05

結論

テスト関数の戻り値がUnitであることを確認すること。

何が起きるか

suspendな関数をテストするために、以下のように書くと戻り値がUnitではなくなります。

// No tests found for given includesの発生するコード
internal class FuncTest {
    @Test
    fun test() = runBlocking {
        // ブロック内の最後の式が戻り値と見做されるので
        // test()の戻り値がAbstractIntegerAssertになってしまう
        Assertions.assertThat(2).isEqualTo(2) 
    }
}

AssertJではassertの戻り値がAssertionクラスです。そのためtest()の戻り値が(上記の例では)AbstractIntegerAssertになります。
jUnitはテスト関数の戻り値にUnitを期待するため、テスト関数を見つけることができずにNo tests found for given includesで例外が発生します。

これを解消するにはtest()の返り値がUnitであることを明示する必要があります。
具体的には以下のような方法になります。

internal class FuncTest {
    @Test
    fun test() = runBlocking<Unit> {
        Assertions.assertThat(2).isEqualTo(2)
    }
}
internal class FuncTest {
    @Test
    fun test(): Unit = runBlocking {
        Assertions.assertThat(2).isEqualTo(2)
    }
}
internal class FuncTest {
    @Test
    fun test() = runBlocking {
        Assertions.assertThat(2).isEqualTo(2)
        Unit
    }
}

jUnitのAssertionsを利用する限りでは戻り値がvoidなのでこのような問題は発生しません。

internal class FuncTest {
    @Test
    fun test() = runBlocking {
        // 返り値がvoidなのでtest()の戻り値もUnitになる
        Assertions.assertEquals(2, 2)
    }
}
0
0
1

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
0
0