Mockito.anyString() crashes with NPE in Kotlin

倖福魔咒の 提交于 2021-02-09 10:53:53

问题


I am using espresso and I want to create a mock response for the content resolver.

When I use:

`when`(context.activity.contentResolver.query(
        ArgumentMatchers.isA(Uri::class.java), 
        ArgumentMatchers.isA(Array<String>::class.java), 
        ArgumentMatchers.anyString(), null, null))
.thenReturn(matrixCursor)

I get the error:

java.lang.NullPointerException: uri 
at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:128)

Is it possible to create the mock response for the content resolver in such cases?


回答1:


That looks like a nullability issue. Mockito does not work that well with nullable types in Kotlin.

There is a library that handles this problem: https://github.com/nhaarman/mockito-kotlin

I'd suggest you to check anyOrNull() here and try something like

ArgumentMatchers.anyOrNull<String>(), isNull(), isNull()

Read this article to gain full understanding of the problem and how to handle it any different scenarios.



来源:https://stackoverflow.com/questions/49081875/mockito-anystring-crashes-with-npe-in-kotlin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!