我尝试在我的单元测试中比较两个 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 类?