SpannableString 不适用于 Android 单元测试

问题描述

我尝试在我的单元测试中比较两个 SpannableStrings 文本,但收到错误

java.lang.RuntimeException: Method toString in android.text.SpannableString not mocked. See http://g.co/androidstudio/not-mocked for details.

调试后,我确认我根本无法在单元测试中使用 SpannableString 类。

测试实施:

    @Test
    fun `When getCredits() returns multiple invites`() = testdispatcher.testCoroutinedispatcher.runBlockingTest {
        //Change mock response
        repository.setMultipleInvitesResponse()

        //Call viewmodel method to return credits
        testdispatcher.testCoroutinedispatcher.pausedispatcher()
        viewmodel.getCredits()
        testdispatcher.testCoroutinedispatcher.resumedispatcher()

        //Get remote SpannableString invites
        val invites = "You have 5 invites"

        // Initialize viewmodel.showInvitesText.value
        val showInvitesTextValue: SpannableString = viewmodel.showInvitesText.value

        //Compare view model showInvitesText.value with invites
        assertEquals(showInvitesTextValue.toString(),invites)
    }

堆栈跟踪:

java.lang.RuntimeException: Method toString in android.text.SpannableString not mocked. See http://g.co/androidstudio/not-mocked for details.

at android.text.SpannableString.toString(SpannableString.java)
at java.lang.String.valueOf(String.java:2994)
at view_model.viewmodelTest$When getCredits() returns multiple invites$1.invokeSuspend(viewmodelTest.kt:113)
at viewmodelTest$When getCredits() returns multiple invites$1.invoke(viewmodelTest.kt)
at kotlinx.coroutines.test.TestBuildersKt$runBlockingTest$deferred$1.invokeSuspend(TestBuilders.kt:50)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.dispatchedTask.run(dispatchedTask.kt:106)
at kotlinx.coroutines.test.TestCoroutinedispatcher.dispatch(TestCoroutinedispatcher.kt:50)
at kotlinx.coroutines.internal.dispatchedContinuationKt.resumeCancellableWith(dispatchedContinuation.kt:305) ...

showInvitesTextValue 变量初始化时发生错误

如何在单元测试中使用 SpannableString 类?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...