当前位置: 首页 > 知识库问答 >
问题:

在Kotlin函数上使用Mokito anyObject()时,指定为non-null的参数为null

梅欣然
2023-03-14
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())

    }
}
java.lang.IllegalArgumentException: Parameter specified as non-null is null: method my.package.InjectedClass.settingDependentObject, parameter dependentObject
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
    }
}

共有1个答案

阎劲
2023-03-14

默认情况下,Kotlin类和成员是final。Mockito不能模拟最终类或方法。因此,当你写:

verify(injectedObject).settingDependentObject(anyObject())

真正的实现被调用,它需要非空参数。

要解决这个问题,要么打开类和方法,要么更好地更改SimpleClass以接受接口作为其构造函数参数,并模拟该接口。

 类似资料: