Kotlin中的模拟扩展功能 [英] Mocking extension function in Kotlin

查看:115
本文介绍了Kotlin中的模拟扩展功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在测试中使用Mockito或PowerMock模拟Kotlin扩展功能?由于它们是静态解析的,应该将它们作为静态方法调用还是作为非静态方法进行测试?

How to mock Kotlin extension function using Mockito or PowerMock in tests? Since they are resolved statically should they be tested as static method calls or as non static?

推荐答案

我认为 MockK 可以为您提供帮助.

I think MockK can help you.

它也支持模拟扩展功能.

您可以使用它来模拟对象范围的扩展:

You can use it to mock object-wide extensions:

data class Obj(val value: Int)

class Ext {
    fun Obj.extensionFunc() = value + 5
}

with(mockk<Ext>()) {
    every {
        Obj(5).extensionFunc()
    } returns 11

    assertEquals(11, Obj(5).extensionFunc())

    verify {
        Obj(5).extensionFunc()
    }
}

如果扩展是模块范围的,这意味着它是在文件中声明的(而不是在class内部),则应以这种方式对其进行模拟:

If you extension is a module-wide, meaning that it is declared in a file (not inside class), you should mock it in this way:

data class Obj(val value: Int)

// declared in File.kt ("pkg" package)
fun Obj.extensionFunc() = value + 5

mockkStatic("pkg.FileKt")

every {
    Obj(5).extensionFunc()
} returns 11

assertEquals(11, Obj(5).extensionFunc())

verify {
    Obj(5).extensionFunc()
}

通过在声明扩展名的包和文件的名称中添加mockkStatic("pkg.FileKt")行(在示例中为pkg.File.kt).

By adding mockkStatic("pkg.FileKt") line with the name of a package and file where extension is declared (pkg.File.kt in the example).

可在此处找到更多信息:网站

More info can be found here: web site and github

这篇关于Kotlin中的模拟扩展功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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