kotlin - 在单元测试中跳过 Kotlin 对象方法调用
问题描述
我有应该用测试覆盖的方法:
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(""))
解决方案
推荐阅读
- javascript - 如何使用 Python Selenium 调用 javascript 函数?
- oracle - 如何为 PL/SQL 中的 dbms 输出打印的值提供别名?
- hash - keccak256 不返回缓冲区
- python - Matplotlib:通过循环将图表保存在 1 个带有 TypeError 的 pdf 文件中:不可散列的类型:'list'
- java - 在 ftp 服务器中不递归列出文件、目录、子文件和子目录的想法
- macos - 如何用锤子勺绑定蓝牙耳机控制点击?
- python - 为什么 Python 日志记录可以在本地 docker 容器中工作,但不能在 AWS 上工作?
- python - 将 Pandas 数据框与相似的列相结合
- python - 使用日期的动态 df len
- ruby-on-rails - 如何使用 Ruby 动态创建 HTML 文件?