MockK Kotlin: Verification failed: call 1 of 1: was not call



我试图基本上测试我的类中的特定方法是否正确调用不同的方法。我将删除所有不需要的代码,所以基本上我的代码如下:

public class Monitor {
protected void onMessage(String message) {
Log.d(TAG, "Detected the message")
changeOptions();
}
protected void changeOptions() {
Log.d("Reached changeOptions() method");
}
}
RunWith(RobolectricTestRunner::class)
class MonitorTest {
private lateinit var mymonitor : Monitor
@MockK private lateinit var mockContext : Context
@Before
fun setup() {
init(this, relaxed = true)
mockkConstructor(Monitor::class)
every { anyConstructed<Monitor>().getApplicationContext() } returns mockContext
mymonitor = Monitor()
mymonitor.init()
}
@Test
fun test_onMessage() {
val testString : String = "hello"
mymonitor.onMessage(testString)
verify(exactly = 1) {mymonitor.changeOptions());
}
}

然而,使用这段代码,我得到以下错误:

java.lang.AssertionError: Verification failed: call 1 of 1: Monitor(mockkConstructor<Monitor>()).changeOptions() was not called.
Calls to same mock:
1) Monitor(mockkConstructor<Monitor>()).getApplicationContext()
2) Monitor(mockkConstructor<Monitor>()).onMessage("hello")

对此有什么建议吗?

注意:我知道changeOptions()方法正在被调用,因为在我的终端输出中,它打印:
TAG "Detected the message"
TAG "Reached changeOptions() method"

为了能够验证执行,类必须是mock或spy,在您的情况下,由于需要执行实际代码,所以应用了spy,它看起来像这样:

@Before
fun setup() {
init(this, relaxed = true)
mockkConstructor(Monitor::class)
every { anyConstructed<Monitor>().getApplicationContext() } returns mockContext
mymonitor = spyK(Monitor())
mymonitor.init()
}

用户UnconfinedTestDispatcher()。这对我来说非常有效。

相关内容

  • 没有找到相关文章