Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter specified as non-null is null when using Mokito anyObject() on Kotlin function

Tags:

mockito

kotlin

My code as below, refering to the solution in https://stackoverflow.com/a/30308199/3286489

import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
import org.mockito.Mockito.*

class SimpleClassTest {

    private fun <T> anyObject(): T {
        Mockito.anyObject<T>()
        return uninitialized()
    }

    private fun <T> uninitialized(): T = null as T
    lateinit var simpleObject: SimpleClass
    @Mock lateinit var injectedObject: InjectedClass


    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
    }

    @Test
    fun testSimpleFunction() {
        simpleObject = SimpleClass(injectedObject)

        verify(injectedObject).settingDependentObject(anyObject())

    }
}

I still have the below error

java.lang.IllegalArgumentException: Parameter specified as non-null is null: method my.package.InjectedClass.settingDependentObject, parameter dependentObject

Did I miss anything?

UPDATED Below is the code tested (simplest form and working)

class SimpleClass(val injectedClass: InjectedClass) {

    fun simpleFunction() {
        injectedClass.settingDependentObject(DependentClass(Response.Builder().build()))
    }
}

open class DependentClass(response: Response) {

}

open class InjectedClass() {
    lateinit var dependentObject: DependentClass

    fun settingDependentObject(dependentObject: DependentClass) {
        this.dependentObject = dependentObject
    }
}
like image 385
Elye Avatar asked May 21 '16 06:05

Elye


1 Answers

By default Kotlin classes and members are final. Mockito cannot mock final classes or methods. Thus when you write:

verify(injectedObject).settingDependentObject(anyObject())

the real implementation is called which requires non null argument.

To fix that either open your class and method or, even better, change SimpleClass to accept an interface as its constructor argument and mock the interface instead.

like image 161
miensol Avatar answered Oct 10 '22 22:10

miensol