FutureShocked
FutureShocked

Reputation: 888

Can Mockito be used to match parameters that are functions in 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

Upvotes: 6

Views: 3252

Answers (3)

FutureShocked
FutureShocked

Reputation: 888

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

Upvotes: 3

kai hello
kai hello

Reputation: 145

you can add

mockedObject = ObjectToMock()

@Before It is the place to initialize. @Test It is the place to test.you can call mockedObject.myFunc()

Upvotes: 0

Maksim Kostromin
Maksim Kostromin

Reputation: 3788

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

Upvotes: 1

Related Questions