Kotlin协程:在测试Android Presenter时切换上下文

问题描述 投票:2回答:4

我最近在我的Android项目中开始使用kotlin协同程序,但我有点问题。很多人会称它为代码味道。

我正在使用一个MVP架构,其协程在我的演示者中启动,如下所示:

// WorklistPresenter.kt
...
override fun loadWorklist() {
    ...
    launchAsync { mViewModel.getWorklist() }
    ...

launchAsyncfunction以这种方式实现(在我的WorklistPresenter类扩展的BasePresenter类中):

@Synchronized
protected fun launchAsync(block: suspend CoroutineScope.() -> Unit): Job {
    return launch(UI) { block() }
}

这个问题是我正在使用依赖于Android Framework的UI协程上下文。如果不进入ViewRootImpl$CalledFromWrongThreadException,我无法将其更改为另一个协程上下文。为了能够对此进行单元测试,我创建了一个具有不同launchAsync实现的BasePresenter副本:

protected fun launchAsync(block: suspend CoroutineScope.() -> Unit): Job {
    runBlocking { block() }
    return mock<Job>()
}

对我来说这是一个问题,因为现在我的BasePresenter必须在两个地方维护。所以我的问题是。如何更改实施以支持简单测试?

android unit-testing kotlin kotlinx.coroutines
4个回答
2
投票

我建议将launchAsync逻辑提取到一个单独的类中,您可以在测试中简单地模拟它。

class AsyncLauncher{

    @Synchronized
    protected fun execute(block: suspend CoroutineScope.() -> Unit): Job {
        return launch(UI) { block() }
    }

}

它应该是您的活动构造函数的一部分,以使其可替换。


3
投票

我最近了解了Kotlin协同程序,教我的那个人向我展示了解决这个问题的好方法。

您可以使用默认实现创建提供上下文的接口:

interface CoroutineContextProvider {
    val main: CoroutineContext
        get() = Dispatchers.Main
    val io: CoroutineContext
        get() = Dispatchers.IO

    class Default : CoroutineContextProvider
}

并且您可以手动或使用注入框架将此(CoroutineContextProvider.Default())注入到presenter构造函数中。然后在您的代码中使用它提供的上下文:provider.main; provider.io;或者你想要定义的任何东西。现在,您可以使用提供程序对象中的这些上下文来使用launchwithContext,因为它们知道它可以在您的应用程序中正常运行,但您可以在测试期间提供不同的上下文。

从您的测试中注入此提供程序的不同实现,其中所有上下文都是Dispatchers.Unconfined

class TestingCoroutineContextProvider : CoroutineContextProvider {
    @ExperimentalCoroutinesApi
    override val main: CoroutineContext
        get() = Dispatchers.Unconfined
    @ExperimentalCoroutinesApi
    override val io: CoroutineContext
        get() = Dispatchers.Unconfined
}

当你模拟暂停函数时,用runBlocking调用它,这将确保所有操作都发生在调用线程(你的测试)中。它解释了here(参见“Unconfined vs confined Dispatcher”部分)。


1
投票

您还可以让您的演示者不了解UI上下文。相反,演示者应该没有上下文。演示者应该只公开suspend函数并让调用者指定上下文。然后,当您从View中调用此演示者协同程序函数时,可以使用UI context launch(UI) { presenter.somethingAsync() }调用它。这样,在测试演示者时,您可以使用runBlocking { presenter.somethingAsync() }运行测试


1
投票

对于其他人来说,这是我最终实现的实现。

interface Executor {
    fun onMainThread(function: () -> Unit)
    fun onWorkerThread(function: suspend () -> Unit) : Job
}

object ExecutorImpl : Executor {
    override fun onMainThread(function: () -> Unit) {
        launch(UI) { function.invoke() }
    }

    override fun onWorkerThread(function: suspend () -> Unit): Job {
        return async(CommonPool) { function.invoke() }
    }
}

我在构造函数中注入Executor并使用kotlins委托来避免样板代码:

class SomeInteractor @Inject constructor(private val executor: Executor)
    : Interactor, Executor by executor {
    ...
}

现在可以互换地使用Executor方法:

override fun getSomethingAsync(listener: ResultListener?) {
    job = onWorkerThread {
        val result = repository.getResult().awaitResult()
        onMainThread {
            when (result) {
                is Result.Ok -> listener?.onResult(result.getOrDefault(emptyList())) :? job.cancel()
                // Any HTTP error
                is Result.Error -> listener?.onHttpError(result.exception) :? job.cancel()
                // Exception while request invocation
                is Result.Exception -> listener?.onException(result.exception) :? job.cancel()
            }
        }
    }
}

在我的测试中,我用这个切换Executor实现。

对于单元测试:

/**
 * Testdouble of [Executor] for use in unit tests. Runs the code sequentially without invoking other threads
 * and wraps the code in a [runBlocking] coroutine.
 */
object TestExecutor : Executor {
    override fun onMainThread(function: () -> Unit) {
        Timber.d("Invoking function on main thread")
        function()
    }

    override fun onWorkerThread(function: suspend () -> Unit): Job {
        runBlocking {
            Timber.d("Invoking function on worker thread")
            function()
        }
        return mock<Job>()
    }
}

对于仪器测试:

/**
 * Testdouble of [Executor] for use in instrumentations tests. Runs the code on the UI thread.
 */
object AndroidTestExecutor : Executor {
    override fun onMainThread(function: () -> Unit) {
        Timber.d("Invoking function on worker thread")
        function()

    }

    override fun onWorkerThread(function: suspend () -> Unit): Job {
        return launch(UI) {
            Timber.d("Invoking function on worker thread")
            function()
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.