如何在Kotlin中模拟和验证Lambda表达? [英] How to mock and verify Lambda expression in Kotlin?

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

问题描述

在Kotlin(和Java 8)中,我们可以使用Lambda表达式删除样板回调接口.例如,

In Kotlin (and Java 8) we can use Lambda expression to remove boilerplate callback interface. For example,

data class Profile(val name: String)

interface ProfileCallback {
  fun onSuccess(profile: Profile)
}

class ProfileRepository(val callback: ProfileCallback) {

  fun getProfile() {
    // do calculation
    callback.onSuccess(Profile("name"))
  }
}

我们可以更改删除ProfileCallback并将其更改为Kotlin的Lambda:

We can change remove ProfileCallback and change it into Kotlin's Lambda:

class ProfileRepository(val callback: (Profile) -> Unit) {

  fun getProfile() {
    // do calculation
    callback(Profile("name"))
  }
}

这可以正常工作,但是我不确定如何模拟然后验证该功能.我有 尝试像这样使用Mockito

This works fine, but I'm not sure how to mock and then verify that function. I have tried using Mockito like this

@Mock
lateinit var profileCallback: (Profile) -> Unit

@Test
fun test() {
    // this wouldn't work
    Mockito.verify(profileCallback).invoke(any())   
}

但它抛出异常:

org.mockito.exceptions.base.MockitoException:ClassCastException 在创建模仿者嘲笑:模仿的类时发生: 'kotlin.jvm.functions.Function1',由classloader加载: 'sun.misc.Launcher$AppClassLoader@7852e922'

org.mockito.exceptions.base.MockitoException: ClassCastException occurred while creating the mockito mock : class to mock : 'kotlin.jvm.functions.Function1', loaded by classloader : 'sun.misc.Launcher$AppClassLoader@7852e922'

如何在Kotlin中模拟和验证Lambda表达?甚至有可能吗?

How to mock and verify Lambda expression in Kotlin? Is it even possible?

推荐答案

以下是使用mockito-kotlin的示例:

给出存储库类

class ProfileRepository(val callback: (Int) -> Unit) {

    fun getProfile() {
        // do calculation
        callback(1)
    }
}

使用mockito-kotlin lib-您可以像这样编写测试模拟lambda:

Using mockito-kotlin lib - you can write test mocking lambdas like this:

@Test
fun test() {
    val callbackMock: (Int) -> Unit = mock()
    val profileRepository = ProfileRepository(callbackMock)

    profileRepository.getProfile()

    argumentCaptor<Int>().apply {
        verify(callbackMock, times(1)).invoke(capture())
        assertEquals(1, firstValue)
    }
}

这篇关于如何在Kotlin中模拟和验证Lambda表达?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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