Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Mockito be used to match parameters that are functions in Kotlin?

Tags:

mockito

kotlin

I have a function with a prototype similar to:

class objectToMock {

    fun myFunc(stringArg: String, booleanArg: Boolean = false, functionArg: (String) -> Any = { 0 }): String

}

I'd like to be able to stub myFunc but can't figure out how to. Something like

@Mock
lateinit var mockedObject: ObjectToMock

@Before
fun setup() {
    MockitoAnnotations.initMocks(this)
    `when`(mockedObject.myFunc(anyString(), anyBoolean(), any())).thenReturn("")
}

Using any() and notNull() both lead to java.lang.IllegalStateException: any() must not be null

like image 971
FutureShocked Avatar asked Jul 16 '18 23:07

FutureShocked


People also ask

Does Mockito work with Kotlin?

Mockito has been around since the early days of Android development and eventually became the de-facto mocking library for writing unit tests. Mockito and Mockk are written in Java and Kotlin, respectively, and since Kotlin and Java are interoperable, they can exist within the same project.

Can the Mockito Matcher methods be used as return values?

Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo. class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.

What is a matcher in Mockito?

What are Matchers? Matchers are like regex or wildcards where instead of a specific input (and or output), you specify a range/type of input/output based on which stubs/spies can be rest and calls to stubs can be verified. All the Mockito matchers are a part of 'Mockito' static class.

What is the use of Mockito Any ()?

Mockito allows us to create mock objects and stub the behavior for our test cases. We usually mock the behavior using when() and thenReturn() on the mock object.


2 Answers

The solution here is to use anyOrNull from https://github.com/nhaarman/mockito-kotlin, or implement that helper yourself.

like image 175
FutureShocked Avatar answered Oct 17 '22 00:10

FutureShocked


Mockito often returns null when calling methods like any(), eq() etcetera. Passing these instances to methods that are not properly mocked, can cause NullPointerExceptions

see: https://github.com/nhaarman/mockito-kotlin/wiki/Parameter-specified-as-non-null-is-null

like image 45
Maksim Kostromin Avatar answered Oct 16 '22 23:10

Maksim Kostromin