簡體   English   中英

Android kotlin 單元測試 - 線程“Test worker @coroutine#4”中的異常

[英]Android kotlin unit test - Exception in thread "Test worker @coroutine#4" io.mockk.MockKException: no answer found for: View(#1)

我正在編寫從 API 獲取數據的演示者的單元測試:

class SearchPresenter constructor(
    private val view: SearchContract.View,
    private val coroutineScope: CoroutineScope,
    private val dispatcherProvider: DispatcherProvider,
    private val userService: UserService
) : SearchContract.Presenter {

    override fun fetchData() {
        coroutineScope.launch(dispatcherProvider.io) {
            val response = withContext(dispatcherProvider.io) {
                userService.getUsers(1u)
            }
            if (response.isSuccessful) {
                view.displayUsers(response.body()!!.data)
            } else {
                view.displayError()
            }
        }
    }
}

我根據上下文(測試與否)使用 2 個不同的調度程序:

interface DispatcherProvider {
    val main: CoroutineDispatcher
    val io: CoroutineDispatcher
    val default: CoroutineDispatcher
}

class DefaultDispatcher : DispatcherProvider {
    override val main: CoroutineDispatcher
        get() = Dispatchers.Main
    override val io: CoroutineDispatcher
        get() = Dispatchers.IO
    override val default: CoroutineDispatcher
        get() = Dispatchers.Default
}

對於我的測試,我使用這個 Dispatcher:

class DispatcherProviderTest : DispatcherProvider {
    override val main: CoroutineDispatcher
        get() = TestCoroutineDispatcher()
    override val io: CoroutineDispatcher
        get() = TestCoroutineDispatcher()
    override val default: CoroutineDispatcher
        get() = TestCoroutineDispatcher()
}

這是我的演示者測試 class:

class SearchPresenterTest : CoroutineBasedTest() {
    lateinit var view: SearchContract.View
    lateinit var presenter: SearchPresenter
    lateinit var dispatcherProvider: DispatcherProvider
    lateinit var userService: UserService


    @Before
    fun setUp() {
        view = mockk()
        userService = mockk(relaxed = true)
        dispatcherProvider = testCoroutineContextProvider
        presenter = SearchPresenter(view, coroutineScope.scope, dispatcherProvider, userService)
    }


    @Test
    fun testSuccess() {
        val users = listOf<UserPreview>(
            UserPreview(
                "testId",
                "testTitle",
                "testFirstName",
                "testLastName",
                "test.jpg"
            )
        )
        coEvery {
            userService.getUsers(1u)
        } answers {
            Response.success(
                Page(
                    users, 1u
                )
            )
        }
        presenter.fetchData()
        verify { view.displayUsers(users) }
    }

這個 class 繼承自 CoroutineBasedTest:

abstract class CoroutineBasedTest {

    @get:Rule
    val coroutineScope = TestCoroutineScopeRule()

    protected val testCoroutineContextProvider = DispatcherProviderTest()


    class TestCoroutineScopeRule : TestWatcher() {

        lateinit var scope: CoroutineScope
        val mainThreadSurrogate = Executors.newSingleThreadExecutor().asCoroutineDispatcher()

        override fun starting(description: Description?) {
            super.starting(description)
            scope = CoroutineScope(Job() + mainThreadSurrogate)
        }

        override fun finished(description: Description?) {
            super.finished(description)
            scope.cancel()
        }
    }

}

我一定對 scope 或調度程序沒有正確清潔有問題。 但我找不到修復它。 當我運行測試時,我有一個成功的結果,但有這個例外:

線程“測試工作者@coroutine#4”中的異常io.mockk.MockKException:沒有找到答案:View(#1).displayUsers([UserPreview(id=testId, title=testTitle, firstName=testFirstName, lastName=testLastName, picture =test.jpg)]) at io.mockk.impl.stub.MockKStub.defaultAnswer(MockKStub.kt:93) at io.mockk.impl.stub.MockKStub.answer(MockKStub.kt:42) at io.mockk. impl.recording.states.AnsweringState.call(AnsweringState.kt:16) at io.mockk.impl.recording.CommonCallRecorder.call(CommonCallRecorder.kt:53) at io.mockk.impl.stub.MockKStub.handleInvocation(MockKStub. kt:266) at io.mockk.impl.instantiation.JvmMockFactoryHelper$mockHandler$1.invocation(JvmMockFactoryHelper.kt:23) at io.mockk.proxy.jvm.advice.Interceptor.call (Interceptor.kt:21) at io.mockk.proxy.jvm.advice.BaseAdvice.handle(BaseAdvice.kt:42) at io.mockk.proxy.jvm.advice.jvm.JvmMockKProxyInterceptor.interceptNoSuper(JvmMockKProxyInterceptor.java:45 ) at com.thefork.challenge.search.SearchContract$View$Subclass0.displayUsers(Unknown Source) at com.thefork.challenge.search.SearchPresenter$fetchData$1.invokeSuspend(SearchPresenter.kt:24) 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:45) at kotlinx.coroutines.internal .DispatchedContinuationKt.resumeCan cellableWith(DispatchedContinuation.kt:322) at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30) at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:25) at kotlinx.coroutines.CoroutineStart .invoke(CoroutineStart.kt:110) at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:126) at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt:56) at kotlinx.coroutines.BuildersKt.launch( Unknown Source) at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch$default(Builders.common.kt:47) at kotlinx.coroutines.BuildersKt.launch$default(Unknown Source) at com.thefork.challenge.search.SearchPresenter.fetchData(SearchPresenter .kt:19) 位於 com.thefork.challenge.search.SearchPresenterTest.testSuccess(SearchPresenterTest.kt:53) 位於 java.base/jdk.internal.reflect.NativeMethodAccessorI( tive Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/ java.lang.reflect.Method.invoke(Method.java:566) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59) at org.junit.internal.runners.model.ReflectiveCallable.run (ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56) at org.Z587F EFE304B8E3505DE89580432C5DDCZ.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.internal.runners.statements. RunAfters.evaluate(RunAfters.java:27) at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:61) at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) at org.junit .runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366) at org.junit.runners.BlockJUnit4ClassRunn er.runChild(BlockJUnit4ClassRunner.java:103) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63) at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331) at org.junit. runners.ParentRunner$1.schedule(ParentRunner.java:79) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329) at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66) at org .junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293) at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) at org.Z587FEFE304B8E3505 DE89580432C5DDCZ.runners.ParentRunner.run(ParentRunner.java:413) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110) at org.gradle.api.internal.tasks. testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38) at org.gradle.api.internal.tasks. testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor .java:62) at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base /jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method .invoke(Method.java:566) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36) at org.gradle.intern al.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33) at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter. java:94) at com.sun.proxy.$Proxy2.processTestClass(Unknown Source) at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:121) at java.base/jdk .internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.Z93F725A07423FE1C889F448B233D21F426Z073D21F425Z073936) FE1C889F448B33D21F46Z.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.gradle.internal.dispatch. ReflectionDispatch.dispatch(ReflectionDispatch.java:36) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection. java:182) at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164) at org.Z8ED1A771BC236C287AD93C 699BFDD2D7Z.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64) at org.gradle.internal. concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:628) at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56) at java.base/java.lang.Thread.run(Thread.java :829) 抑制:kotlinx.coroutines.DiagnosticCoroutineContextException: [CoroutineId(4), "coroutine#4":StandaloneCoroutine{Cancelling}@34af8dd6, TestCoroutineDispatcher[scheduler=kotlinx.coroutines.test.TestCoroutineScheduler@6637b783]] 9 秒內構建成功

您是否嘗試過為相關呼叫添加“答案”?

coEvery { 
    view.displayUsers(users)
} answers { 
    // some response
}

這可能會使錯誤日志遠離 go。

至於即使有錯誤測試通過,當異常本身發生在不在當前線程上運行的后台協程中時,通常會發生這種情況。 這是因為在測試中,后台線程的“默認未捕獲線程異常處理程序”只會記錄一個錯誤。 您可以嘗試將測試包裝在類似的東西中

dispatcherProvider.io.runBlockingTest {
   ...
}

看看這是否有助於使錯誤浮出水面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM