用kotlin在Android单元测试中模拟对象-any()给出null [英] Mock object in Android Unit test with kotlin - any() gives null

查看:171
本文介绍了用kotlin在Android单元测试中模拟对象-any()给出null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试我的课程,我需要模拟一个static课程.我的代码如下:

I'm trying to test my classes and I need to mock a static class. My code is the following:

PowerMockito.mockStatic(ToolTipUtil::class.java)
PowerMockito.`when`(ToolTipUtil.wasToolTipShown(any(Context::class.java), "")).thenReturn(true)
val context = mock(Context::class.java)
presenter.onResume(context)
verify(view).setMenuButtonShown(eq(false))

但是在第二行中会引发错误:

But in the second line it throws an error:

"java.lang.IllegalStateException: any(Context::class.java) must not be null"

我尝试使用 mockito-kotlin

I've tried with mockito-kotlin and befriending-kotlin-and-mockito with no exit. Do you know how to fix it?

推荐答案

当您调用any()时,Mockito通常返回null,这会破坏kotlin的非null参数.

Mockito often returns null when you call any() and that breaks kotlin's not null parameters.

在Mockito-kotlin中,它们有一个单独的函数,称为

In mockito-kotlin they have a separate function for it, called anyOrNull().

您还可以创建自己的函数

You can also create your own function, here they say that this should also work.

/**
 * Returns Mockito.any() as nullable type to avoid java.lang.IllegalStateException when
 * null is returned.
 */
fun <T> any(): T = Mockito.any<T>()  

这篇关于用kotlin在Android单元测试中模拟对象-any()给出null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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