[英]MockK: How to mock an already tested method called inside another method under test (Kotlin)
[英]MockK Kotlin: Verification failed: call 1 of 1: was not called
我试图从本质上测试我的类中的特定方法是否正确调用了不同的方法。 我将删除所有不需要的代码,所以基本上我的代码如下:
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"
为了能够验证执行,该类必须是模拟或间谍,在您的情况下间谍适用,因为您需要执行真正的代码,它看起来像这样:
@Before
fun setup() {
init(this, relaxed = true)
mockkConstructor(Monitor::class)
every { anyConstructed<Monitor>().getApplicationContext() } returns mockContext
mymonitor = spyK(Monitor())
mymonitor.init()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.