因此,我有以下代码:
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方法甚至没有被调用。
发布于 2019-12-23 13:16:40
这可能是因为KotlinTest在被认为是测试的内容和创建Spec实例时与JUnit不同。
KotlinTest的默认行为是在每次执行时创建Spec的单个实例。由于这个原因,您的模拟程序不会在执行之间重新设置,因为您可能是在class level中创建它们的。
要解决这个问题,您可以做的是在测试中执行mockk,或者在每次执行测试时将隔离模式更改为创建Spec。
默认的isolationMode是IsolationMode.SingleInstance。您可以通过重写Spec函数在isolationMode本身上更改它:
class MySpec : BehaviorSpec() {
init {
Given("XX") {
Then("YY") // ...
}
}
override fun isolationMode() = IsolationMode.InstancePerTest
}您也可以在ProjectConfig中更改它。如果你需要解释如何在那里做,检查ProjectConfig上的文档
另一种方法是清除afterTest方法上的模拟:
class MySpec : BehaviorSpec() {
init {
Given("XX") {
Then("YY") // ...
}
}
override fun afterTest(testCase: TestCase, result: TestResult) {
clearAllMocks()
}
}但我不知道在用例中这是怎么回事。
发布于 2019-12-23 08:26:02
clear方法来重置模拟的状态。有关更多信息,请查看这个相关的问题和莫克氏文档。beforeEach这样的生命周期方法,您可以重写这些方法来重置模拟(使用clear)。在扩展BehaviourSpec时,您应该能够重写这些方法,否则请确认如何为不同的测试风格执行此操作,以避免混淆。发布于 2020-11-11 21:08:09
若要在每次测试后清除模拟,可以提供一个项目范围的侦听器:
import io.kotest.core.listeners.TestListener
import io.kotest.core.spec.AutoScan
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestResult
import io.mockk.clearAllMocks
@AutoScan
class MockkClearingTestListener : TestListener {
override suspend fun afterEach(testCase: TestCase, result: TestResult) = clearAllMocks()
}例如,这适用于WordSpec中的每一个叶子,也应该适用于BehaviorSpec。
https://stackoverflow.com/questions/59442266
复制相似问题