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())

    }
}

我仍然有下面的错误

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

我错过什么了吗?

UPDATED

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
    }
}

推荐答案

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

verify(injectedObject).settingDependentObject(anyObject())

需要非空参数的real implementation is called.

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.

Kotlin相关问答推荐

数据流弹性模板失败,出现错误&未知非复合转换urn";

Mockk:对同一函数进行两次存根会忽略第一个行为

为什么使用 return instance ?: synchronized(this) { instance ?: PreferenceParameterState(context) } 时无法获得单例?

将 java Optional 转换为 Kotlin Arrow Option

mutableStateOf 在 Jetpack Compose 中不记住 API 的情况下保持重组后的值

我什么时候可以在 LazyList 或 Column 的范围内使用 Composable?

你怎么知道什么时候需要 yield()?

类型是什么意

在 kotlin 中写入 parcer 可空值

Anko 中的水平线性布局

Kotlin 中的 Java Scanner 相当于什么?

Kotlin 中 lambda 表达式中的默认参数

是否可以在 kotlin 中嵌套数据类?

在 Kotlin 中取最后 n 个元素

kotlin:扩展方法和空接收器

将 Android Studio 升级到 3.1.0 后的 Android Support 插件错误

如果我可以将 Flow 和 StateFlow 与生命周期范围 \ viewLifecycleOwner.lifecycleScope 一起使用,那么在 ViewModel 中使用 LiveData 有什么意义

Kotlin扩展函数与成员函数?

使用 java lambda 调用 kotlin 函数时,Kotlin 无法访问 kotlin.jvm.functions.Function1

如何在 Intellij Idea 中运行 Kotlin 函数