1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【MockK】ジェネリクスが絡む関数でany()しているのにio.mockk.MockKException: no answer found for: ~が出る状況への対処【Kotlin】

Posted at

TL;DR

every内でany()を指定しているにも関わらず、io.mockk.MockKException: no answer found for: ~となる場合は、any</* 引数として渡したい型 */>()と修正することで解決できるかもしれません。
具体的には、fun func(...): AnyJavaならObject)とfun <T> func(...): Tのような定義が有る場合です。

状況

下記のSampleクラスに定義したfuncメソッドの内、KClassを引数に取る方をモックしようとしました。

class Sample {
    fun <T : Any> func(value: KClass<T>): T = /* Tの生成処理 */

    fun func(value: String): Any = /* Anyを返すような処理 */
}

所が、下記のテストコードでは、モックしたはずのfunc関数を呼び出した所でテストが失敗しました。
エラーメッセージはio.mockk.MockKException: no answer found for: Sample(#1).func(Target)となっていました。

class Test {
    @Test
    fun test() {
        val sample = mockk<Sample>()
        every { sample.func(any()) } returns Target()

        // ここで落ちる
        val result = sample.func(Target::class)

        assertEquals(Target(), result)
        verify(exactly = 1) { sample.func(Target::class) }
    }
}

対処

以下のようにany()にジェネリクスを指定してやることで解決します。

class Test {
    @Test
    fun test() {
        val sample = mockk<Sample>()
        // ジェネリクス指定を追加
        every { sample.func(any<KClass<*>>()) } returns Target()

        val result = sample.func(Target::class)

        verify(exactly = 1) { sample.func(Target::class) }
    }
}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?