用Kotlin和Mockito模拟通用接口 [英] Mocking generic interfaces with Kotlin and Mockito

查看:94
本文介绍了用Kotlin和Mockito模拟通用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Mockito在Kotlin中模拟通用接口.但是到目前为止,我还没有找到自然的解决方案.鉴于:

I am trying to mock a generic interface in Kotlin using Mockito. But so far I have found no natural solution. Given:

interface X<T> {
    fun x(): T
}

fun f(x: X<Int>) = x.x()

我可以使用以下任意一个模拟X:

I could mock X with any of the following:

  1. val x = f(Mockito.mock(X::class.java) as X<Int>)

但这会生成未经检查的演员表"警告.

But that would generate an "unchecked cast" warning.

@Mock lateinit var x: X<Int>

但是我不想使用@Mock批注,因为我希望字段最终输入.

But I do not want to use the @Mock annotation because I like to have my fields final.

引入一个辅助函数,如mockito-kotlin库确实:

Introduce a helper function, as the mockito-kotlin library does:

inline fun <reified T : Any> mock(): T = Mockito.mock(T::class.java)!!

然后这样称呼它:

val x: X<Int> = mock()

但是我不想使用辅助函数.

But I do not want to use helper functions.

是否存在一种优雅的纯Kotlin方法来模拟Mockito的通用接口? (我希望版本1.不带警告.)

Is there an elegant pure Kotlin way to mock a generic interface with Mockito? (I would prefer a version of 1. without the warning.)

推荐答案

只需使用 mockito-kotlin 项目.该项目包含所有必须具备的模仿者助手.并且还支持Mockito 2.1.

Just use mockito-kotlin project. This project contains all must have helpers for mockito. And supports mockito 2.1 as well.

已更新.要处理不熟练的演员",请使用修饰的类型参数.

Upd. To deal with "uncheked cast" use Reified type parameters.

您说的是但是我不想使用辅助函数."但是为什么呢?这是内联函数,因此在编译时将在所有调用站点上内联.

You say that "But I do not want to use helper functions.", but why? This is inline function, so in compile time function will be inlined at all call sites will.

这篇关于用Kotlin和Mockito模拟通用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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