Reputation: 3242
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"
I've tried with mockito-kotlin and befriending-kotlin-and-mockito with no exit. Do you know how to fix it?
Upvotes: 21
Views: 14922
Reputation: 8585
Mockito often returns null when you call any()
and that breaks kotlin's not null parameters.
In mockito-kotlin they have a separate function for it, called anyOrNull().
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>()
Upvotes: 40
Reputation: 465
Add the following code in your test class:
private fun <T> any(type : Class<T>): T {
Mockito.any(type)
return uninitialized()
}
private fun <T> uninitialized(): T = null as T
Upvotes: 5
Reputation: 3976
When calling mock(), you don't have to pass in the class instance anymore. If the type can be inferred, you can just write:
val mock : MyClass = mock()
If the type cannot be inferred directly, use:
val mock = mock<MyClass>()
Hope it will help you!!
Upvotes: -1