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?
If a method return type is a custom class, a mock returns null because there is no empty value for a custom class. RETURN_MOCKS will try to return mocks if possible instead of null . Since final class cannot be mocked, null is still returned in that case.
Test structure Each test should be created from the following blocks: Arrange/Given - in which we will prepare all needed data required to perform test. Act/When - in which we will call single method on tested object. Assert/Then - in which we will check result of the test, either pass or fail.
So in simple words, mocking is creating objects that simulate the behavior of real objects. In Android, there are a lot of frameworks used for mocking in unit testing, such as PowerMock, Mockito, EasyMock, etc.
We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.
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>()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With