使用 kotlin 在 Android 单元测试中模拟对象 - any() 给出 null

2023-02-17移动开发问题
25

本文介绍了使用 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 和 befriending-kotlin-and-mockito 没有退出.你知道怎么解决吗?

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 中,他们有一个单独的函数,称为 anyOrNull().

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

您也可以创建自己的函数,here 他们说这也应该有效.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何开启 Cocos2D CCLOG Debug 模式?
How to turn on Cocos2D CCLOG Debug mode?(如何开启 Cocos2D CCLOG Debug 模式?)...
2024-08-12 移动开发问题
10

收到消息“警告:在正常情况下,_fillInQueueWithExtraSpace:.."和 MPMovieP
Got the message quot;WARNING: under normal conditions, _fillInQueueWithExtraSpace:..quot; and MPMoviePlayer rotation not work in iPad IOS 5.1(收到消息“警告:在正常情况下,_fillInQueueWithExtraSpace:..和 MPMoviePlayer 旋转在 iPad IOS 5.1 中...
2024-08-12 移动开发问题
6

在 cocos2d 中平滑拖动一个 Sprite - iPhone
Smoothly drag a Sprite in cocos2d - iPhone(在 cocos2d 中平滑拖动一个 Sprite - iPhone)...
2024-08-12 移动开发问题
10

如何抓取 b2Body 并在屏幕上移动它?(cocos2d,box2d,iphone)
How to grab a b2Body and move it around the screen? (cocos2d,box2d,iphone)(如何抓取 b2Body 并在屏幕上移动它?(cocos2d,box2d,iphone))...
2024-08-12 移动开发问题
12

用 ccTouchesMoved 方法移动 CCCamera?(cocos2d,iphone)
Move CCCamera with the ccTouchesMoved method? (cocos2d,iphone)(用 ccTouchesMoved 方法移动 CCCamera?(cocos2d,iphone))...
2024-08-12 移动开发问题
2

Cocos2d 人像模式在 iPhone 上不起作用
Cocos2d portrait mode not working on iPhone(Cocos2d 人像模式在 iPhone 上不起作用)...
2024-08-12 移动开发问题
2