如何模拟Kotlin单例对象? [英] How to mock a Kotlin singleton object?

查看:107
本文介绍了如何模拟Kotlin单例对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Given a Kotlin singleton object and a fun that call it's method

object SomeObject {
   fun someFun() {}
}

fun callerFun() {
   SomeObject.someFun()
}

有没有办法模拟对SomeObject.someFun()的调用?

Is there a way to mock call to SomeObject.someFun()?

推荐答案

仅使您对象实现接口,然后即可使用任何模拟库对对象进行模拟.这是Junit + Mockito + Mockito-Kotlin 的示例:

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:

Or in case if you want mock SomeObject inside callerFun:

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单例对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆