是否可以在 Kotlin 中使用 Mockito? [英] Is it possible to use Mockito in Kotlin?

查看:44
本文介绍了是否可以在 Kotlin 中使用 Mockito?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临的问题是 Matchers.anyObject() 返回 null.当用于模拟只接受不可为空类型的方法时,它会导致抛出不应为空"异常.

The problem I'm facing is that Matchers.anyObject() returns null. When used to mock method that only accepts non-nullable types it causes a "Should not be null" exception to be thrown.

`when`(mockedBackend.login(anyObject())).thenAnswer { invocationOnMock -> someResponse }

模拟方法:

public open fun login(userCredentials: UserCredentials): Response

推荐答案

有两种可能的解决方法:

There are two possible workarounds:

private fun <T> anyObject(): T {
    Mockito.anyObject<T>()
    return uninitialized()
}

private fun <T> uninitialized(): T = null as T

@Test
fun myTest() {
    `when`(mockedBackend).login(anyObject())).thenAnswer { ... }
}

另一种解决方法是

private fun <T> anyObject(): T {
    return Mockito.anyObject<T>()
}

@Test
fun myTest() {
    `when`(mockedBackend).login(anyObject())).thenAnswer { ... }
}

这是更多讨论本主题,首先建议解决方法.

Here is some more discussion on this topic, where the workaround is first suggested.

这篇关于是否可以在 Kotlin 中使用 Mockito?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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