junit AndroidKotlin单元测试-线程“Test worker@coroutine#4”中出现异常io.mockk. MockK异常:未找到以下项的答案:视图(#1)

vbkedwbf  于 2022-11-11  发布在  Android
关注(0)|答案(1)|浏览(124)

我正在编写一个演示器的单元测试,该演示器从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 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) }
    }

此类继承自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()
        }
    }

}

我肯定是遇到了作用域或调度程序未正确清理的问题。但我找不到修复程序。运行测试时,我得到了成功的结果,但出现了以下异常:

Exception in thread "Test worker @coroutine#4" io.mockk.MockKException: no answer found for: 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.resumeCancellableWith(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) at com.thefork.challenge.search.SearchPresenterTest.testSuccess(SearchPresenterTest.kt:53) 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.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.junit.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.BlockJUnit4ClassRunner.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.junit.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.internal.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) 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.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.gradle.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) Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [CoroutineId(4), "coroutine#4":StandaloneCoroutine{Cancelling}@34af8dd6, TestCoroutineDispatcher[scheduler=kotlinx.coroutines.test.TestCoroutineScheduler@6637b783]] BUILD SUCCESSFUL in 9s

l0oc07j2

l0oc07j21#

您是否尝试过为有问题的呼叫添加“应答”?

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

这可能会让错误日志消失。
至于即使有错误也能通过测试,当异常本身发生在后台协程中,而后台协程没有在当前线程上运行时,这种情况经常会发生。这是因为在测试中,后台线程的“默认未捕获线程异常处理程序”只会记录一个错误。您可以尝试将测试 Package 在类似于

dispatcherProvider.io.runBlockingTest {
   ...
}

看看这是否能让错误浮出水面。

相关问题