LoginSignup
0
1

More than 1 year has passed since last update.

privateメソッドのテスト

Posted at

前提

privateメソッドのテストをそもそも書くべきかは要検討!
privateメソッドのモック化やverifyの確認に詰まったので記しておきます。

テスト対象のクラス

Kotlin
class PrivateMethodClass {
    fun publicMethod(): String {
        privateMethodReturnNothing()
        return privateMethodReturnString("test")
    }

    // 戻り値ありのprivateメソッド
    private fun privateMethodReturnString(text: String): String {
        return text
    }

    // 戻り値なしのprivateメソッド
    private fun privateMethodReturnNothing() {
        privateMethodReturnString("hoge")
    }
}

テストコード

Kotlin
@Test
fun publicMethodTest() {
    val privateMethodClass = spyk(PrivateMethodClass(), recordPrivateCalls = true)

    // 戻り値ありのprivateメソッドのモック化
    every {
        privateMethodClass["privateMethodReturnString"](allAny<String>())
    } returns "test"

    // 戻り値ありのprivateメソッドのモック化
    every {
        privateMethodClass["privateMethodReturnNothing"]()
    }.answers { nothing }

    // テスト実施
    assertEquals("test", privateMethodClass.publicMethod())
    verify {
        privateMethodClass["privateMethodReturnString"](allAny<String>())
        privateMethodClass["privateMethodReturnNothing"]()
    }
}

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