Mock object in Android Unit test with kotlin - any() gives null(使用 kotlin 在 Android 单元测试中模拟对象 - any() 给出 null)
问题描述
我正在尝试测试我的类,我需要模拟一个 static
类.我的代码如下:
I'm trying to test my classes and I need to mock a static
class. My code is the following:
PowerMockito.mockStatic(ToolTipUtil::class.java)
PowerMockito.`when`(ToolTipUtil.wasToolTipShown(any(Context::class.java), "")).thenReturn(true)
val context = mock(Context::class.java)
presenter.onResume(context)
verify(view).setMenuButtonShown(eq(false))
但是在第二行它会抛出一个错误:
But in the second line it throws an error:
"java.lang.IllegalStateException: any(Context::class.java) must not be null"
我已经尝试过 mockito-kotlin 和 befriending-kotlin-and-mockito 没有退出.你知道怎么解决吗?
I've tried with mockito-kotlin and befriending-kotlin-and-mockito with no exit. Do you know how to fix it?
推荐答案
当你调用 any()
时,Mockito 经常返回 null,这会破坏 kotlin 的非 null 参数.
Mockito often returns null when you call any()
and that breaks kotlin's not null parameters.
在 mockito-kotlin 中,他们有一个单独的函数,称为 anyOrNull().
In mockito-kotlin they have a separate function for it, called anyOrNull().
您也可以创建自己的函数,here 他们说这也应该有效.
You can also create your own function, here they say that this should also work.
/**
* Returns Mockito.any() as nullable type to avoid java.lang.IllegalStateException when
* null is returned.
*/
fun <T> any(): T = Mockito.any<T>()
这篇关于使用 kotlin 在 Android 单元测试中模拟对象 - any() 给出 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 kotlin 在 Android 单元测试中模拟对象 - any()


基础教程推荐
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01