我有测试应该覆盖的方法:
private fun handleLogin(triple: Triple<String?, CurrentUserData?, List<ServerError>?>?) {
emitProgressState()
Emarsys.setContact(triple?.second?.userId.toString())
if (shouldRedirectToRegistration(triple?.first, triple?.third))
_navigation.value = Route.RegistrationUrl(triple?.first)
else _navigation.value = Route.Main(
userId = triple?.second?.userId.toString(),
borrowerId = triple?.second?.borrowerId.toString()
)
}
这里有一个 Kotlin 对象方法的调用:
Emarsys.setContact(triple?.second?.userId.toString())
这个对象是在代码中以一种特殊的方式配置的,所以在单元测试中,我只需要跳过它的调用。为此,我在测试用例中添加了这样一行:
Mockito.`when`(Emarsys.setContact(Mockito.anyString())).thenReturn(Unit)
但是 setContact
方法体仍然被执行。我做错了什么?
UPD
尝试用 mockStatic
val emarsysMock = Mockito.mockStatic(Emarsys::class.java)
emarsysMock.`when`<Unit> {
Emarsys.setContact("")
}
但收到错误
'setContact' is a *void method* and it *cannot* be stubbed with a *return value*!
Voids are usually stubbed with Throwables:
doThrow(exception).when(mock).someVoidMethod();
If you need to set the void method to do nothing you can use:
doNothing().when(mock).someVoidMethod();
For more information, check out the javadocs for Mockito.doNothing().
***
也尝试用 doNothing
进行模拟,但它仍然调用真实对象的方法,而不是存根:
doNothing().`when`(Emarsys.setContact(""))