3
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 3 years have passed since last update.

MockKでモックが呼ばれないことをテストする

Posted at

MockKでテストを書いていく上で、モックが呼ばれないことをテストしたかったのでメモ。
(Mockitoで言うところの verifyZeroInteractions です。)

wasNot called を使えばOK

テストしたいモックが mockObject だとすると、下記のように書けばOKです。

verify {
    mockObject wasNot called
}

英文ぽくなって、かなりいいですね:relaxed:


以下、サンプルコードを記載します。

サンプルコード

Hoge というクラスがあり、 fuga() では Logger が呼ばれ、piyo() では Logger 呼ばれないようになっています。

interface Logger {
    fun log()
}

class Hoge(private val logger: Logger) {

    fun fuga() {
        logger.log()
    }

    fun piyo() {
        // NO LOG
    }
}

これをテストする場合は…、

class HogeTest {

    @Test
    fun fuga_Loggerが呼ばれる() {
        val logger = mockk<Logger>(relaxed = true)
        val hoge = Hoge(logger)

        hoge.fuga()

        verify {
            logger.log() // log()が呼ばれることを検証
        }
    }

    @Test
    fun piyo_Loggerが呼ばれない() {
        val logger = mockk<Logger>(relaxed = true)
        val hoge = Hoge(logger)

        hoge.piyo()

        verify {
            logger wasNot called // loggerが呼ばれないことを検証
        }
    }
}

という感じになります。

3
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
3
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?