kotlinmockitomockito-kotlin

How to create ArgumentMatchers.any(type: Class<T>) for testing in Kotlin?


I'm trying to unit test a class that uses the following service:

parserService.parseJsonStringToModel(json: String, adapterClass: Class<T>): T?

My first approach was to use ArgumentMatchers to implement unit testing as follows:

Mockito.`when`(parserService.parseJsonStringToModel(ArgumentMatchers.any(), ArgumentMatchers.any<CreateAccountRequest>().javaClass)).thenReturn(null)

Since ArgumentMatchers.any() returns null in Kotlin, that produces NullPointerException for non nullable types. So I give a try to Mockito-Kotlin library to avoid this problem. The approach looks like following:

whenever(parserService.parseJsonStringToModel(any(), any<CreateAccountRequest>().javaClass)).thenReturn(null)

Used library solves the problem for first argument but still produces NullPointerException for passed second argument.

So, how can I create an ArgumentMatchers for Class<T> type arguments?


Solution

  • You could simply create a matcher directly for Class<CreateAccountRequest>:

    whenever(
        parserService.parseJsonStringToModel(
            any(),
            any<Class<CreateAccountRequest>>()
        )
    ).thenReturn(null)