問題描述
我正在嘗試測(cè)試我的類,我需要模擬一個(gè) 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))
但是在第二行它會(huì)拋出一個(gè)錯(cuò)誤:
But in the second line it throws an error:
"java.lang.IllegalStateException: any(Context::class.java) must not be null"
我已經(jīng)嘗試過 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?
推薦答案
當(dāng)你調(diào)用 any()
時(shí),Mockito 經(jīng)常返回 null,這會(huì)破壞 kotlin 的非 null 參數(shù).
Mockito often returns null when you call any()
and that breaks kotlin's not null parameters.
在 mockito-kotlin 中,他們有一個(gè)單獨(dú)的函數(shù),稱為 anyOrNull().
In mockito-kotlin they have a separate function for it, called anyOrNull().
您也可以創(chuàng)建自己的函數(shù),here 他們說這也應(yīng)該有效.
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>()
這篇關(guān)于使用 kotlin 在 Android 單元測(cè)試中模擬對(duì)象 - any() 給出 null的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!