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

时间:2018-03-07 09:50:57

标签: android unit-testing kotlin mockito

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

    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))

但是在第二行它会抛出一个错误:

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

我尝试过mockito-kotlinbefriending-kotlin-and-mockito但没有退出。你知道怎么解决吗?

3 个答案:

答案 0 :(得分:6)

当您调用any()时,Mockito经常返回null,并且会破坏kotlin的非null参数。

在mockito-kotlin中,他们有一个独立的功能,称为anyOrNull()

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

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

答案 1 :(得分:1)

在测试类中添加以下代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1.0">
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.5"
            android:layout_height="wrap_content"
            android:id="@+id/message_user"
            android:textStyle="normal|bold"/>
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.5"
            android:layout_height="wrap_content"
            android:id="@+id/message_time"
            android:textStyle="normal|bold"/>
    </LinearLayout>
    <TextView
        android:layout_marginTop="5dp"
        android:layout_width="wrap_content"
        android:textSize="18sp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/message_user"
        android:layout_alignParentEnd="true"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:id="@+id/message_text"
        android:textStyle="normal|bold"/>

</LinearLayout>

答案 2 :(得分:-1)

调用mock()时,您不必再传入类实例。如果可以推断出类型,你可以写:

val mock : MyClass = mock()

如果无法直接推断出类型,请使用:

val mock = mock<MyClass>()

希望它能帮到你!!