Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock object in Android Unit test with kotlin - any() gives null

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?

like image 201
aloj Avatar asked Mar 07 '18 09:03

aloj


People also ask

Why is a mock null?

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.

How do you write unit test cases in Kotlin?

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.

What is mocking Kotlin?

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.

How do you mock objects JUnit?

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.


1 Answers

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>()  
like image 103
TpoM6oH Avatar answered Sep 27 '22 17:09

TpoM6oH