gpt4 book ai didi

callback - 在 kotlin 中,如何模拟包装回调的挂起函数?

转载 作者:行者123 更新时间:2023-12-02 21:53:50 26 4
gpt4 key购买 nike

假设有一个带有回调的接口(interface):

interface SomeInterface {
fun doSomething(arg: String, callback: (Exception?, Long) -> Unit)
}

我将其扩展为这样的挂起函数:

suspend fun SomeInterface.doSomething(arg: String): Long = suspendCoroutine { cont ->
this.doSomething(arg) { err, result ->
if (err == null) {
cont.resume(result)
} else {
cont.resumeWithException(err)
}
}
}

我想在测试中模拟这个,但失败了。理想情况下,我想使用这样的东西:

@Test
fun checkService() {
runBlocking {
val myService = mock<SomeInterface>()
whenever(myService.doSomething(anyString())).thenReturn(1234L)
val result = myService.doSomething("")
assertEquals(result, 1234L)
}
}

上面的语法失败并出现mockito异常,因为它需要回调的匹配器。

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 1 recorded:

我如何模拟这样的挂起函数?如果类似的语法不可能,我如何才能使用所需的参数进行模拟回调,以便在整个代码中使用的挂起变量在测试期间返回所需的结果?

更新:当它是扩展功能时,似乎不可能。基于Marko Topolnik的评论,我认为这是因为扩展只是一个静态函数,超出了mockito的能力。

当挂起函数是成员函数时,它会按照我原来的语法按预期工作。

这里是一些演示代码的要点: https://gist.github.com/mirceanis/716bf019a47826564fa57a77065f2335

最佳答案

我建议使用MockK用于您的测试,这对协程更加友好。

要模拟协程,您可以使用 coEveryreturns ,如下所示:

val interf = mockk<SomeInterface>()
coEvery { a.doSomething(any()) } returns Outcome.OK

关于callback - 在 kotlin 中,如何模拟包装回调的挂起函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51673534/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com