Mockk的Kotlintest如何清除验证计数

问题描述 投票:0回答:2

所以我有以下代码:

When("SMS with location update command is received") {
        every {
            context.getString(R.string.location_sms, any(), any(), any(), any())
        } returns "loc"
        mainServiceViewModel.handleSms(SmsMessage("123", "location"))

        Then("SMS with location is sent to specified phone number") {
            verify(exactly = 1) {
                smsRepository.sendSms("+123", "loc")
            }
        }
    }

    When("motion is detected") {

        Then("information SMS is sent to specified phone number") {
            verify(exactly = 1) {
                smsRepository.sendSms("+123", any())
            }
        }
    }

问题在于,即使第二种情况都不采取任何措施,两种情况都通过了。我希望第二种情况失败,因为甚至没有调用sendSms方法。

  1. 如何重置smsRepository验证计数?
  2. 如何在每种情况下重设该计数?
unit-testing kotlin bdd mockk kotlintest
2个回答
0
投票
  1. 您应该尝试提供的各种clear方法来重置模拟状态。检查this related questionMockK's docs了解更多信息。

  2. 检查documentation about test listeners。基本上,每个测试规范类都提供诸如beforeEach之类的生命周期方法,您可以重写它们以重置模拟(使用clear)。在扩展BehaviourSpec时,您应该能够覆盖这些方法,否则请针对不同的testing styles确认如何执行此操作,以免造成混淆。


0
投票

[这可能是由于KotlinTest与JUnit在被认为是测试以及创建Spec实例时不同。

KotlinTest的默认行为是每次执行都创建Spec的单个实例。因此,您的模拟不会在两次执行之间重置,因为您可能已在class level中创建了它们。


要解决此问题,您可以做的是在测试内部执行mockk,或者将isolation mode更改为每次执行测试时都会创建Spec的内容。

默认isolationModeIsolationMode.SingleInstance。您可以通过覆盖Spec功能在isolationMode本身上进行更改:

class MySpec : BehaviorSpec() {

    init {
        Given("XX") { 
            Then("YY") // ...
        }
    }

    override fun isolationMode() = IsolationMode.InstancePerTest

}

您也可以在ProjectConfig中进行更改。如果您需要在那里的操作说明,请check the docs on ProjectConfig

© www.soinside.com 2019 - 2024. All rights reserved.