用Kotlin和Mockito模拟通用接口

编程入门 行业动态 更新时间:2024-10-27 16:30:57
本文介绍了用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:

  • 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模拟通用接口

    本文发布于:2023-10-31 07:07:47,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1545382.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:接口   Kotlin   Mockito

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!