给出一个Kotlin单例对象和调用它的方法的乐趣

object SomeObject {
   fun someFun() {}
}

fun callerFun() {
   SomeObject.someFun()
}

有没有办法模拟拨打SomeObject.someFun()的电话?

推荐答案

Just make you object implement an interface, than you can mock you object with any mocking library. Here example of Junit + Mockito + Mockito-Kotlin:

import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Assert.assertEquals
import org.junit.Test

object SomeObject : SomeInterface {
    override fun someFun():String {
        return ""
    }
}

interface SomeInterface {
    fun someFun():String
}

class SampleTest {

    @Test
    fun test_with_mock() {
        val mock = mock<SomeInterface>()

        whenever(mock.someFun()).thenReturn("42")

        val answer = mock.someFun()

        assertEquals("42", answer)
    }
}

或者如果你想在callerFun中模拟SomeObject:

import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Assert.assertEquals
import org.junit.Test

object SomeObject : SomeInterface {
    override fun someFun():String {
        return ""
    }
}

class Caller(val someInterface: SomeInterface) {
    fun callerFun():String {
        return "Test ${someInterface.someFun()}"
    }
}

// Example of use
val test = Caller(SomeObject).callerFun()

interface SomeInterface {
    fun someFun():String
}

class SampleTest {

    @Test
    fun test_with_mock() {
        val mock = mock<SomeInterface>()
        val caller = Caller(mock)

        whenever(mock.someFun()).thenReturn("42")

        val answer = caller.callerFun()

        assertEquals("Test 42", answer)
    }
}

Kotlin相关问答推荐

在Kotlin中处理结果的高阶函数

在intellij中使用kotlin符号和floordiv

在调用父构造函数之前重写类属性

多模块Kotlin项目中的FreeFair

从 Kotlin 的父类获取函数注解

在 Kotlin 中将两个字节转换为 UIn16

为什么 <= 可以应用于 Int 和 Long,而 == 不能?

Kotlin .如何用从 1 到 90 的 5 个唯一数字填充列表中的每一行?

Kotlin 中的 maxOf() 和 max() 方法有什么区别?

在kotlin中匹配多个变量

如果带注释的成员未被特定块包围,则发出 IDE 警告

如果不为空,则为 builder 设置一个值 - Kotlin

.indices 在 kotlin 中的含义是什么?

如何使用 gradle 脚本 Kotlin 构建文件构建可运行的 ShadowJar?

Kotlin 的类型具体化使哪些在 Java 或 Scala 中无法实现的成为可能?

如何在Kotlin中创建填充空值的通用数组?

类型不匹配:推断类型为 LoginActivity 但应为 LifecycleOwner

如何将vararg作为数组传递给Kotlin中的函数?

RxJava - 每秒发出一个 observable

类型推断失败:RecyclerViewActions.scrollTo()