Kotlin 协程:在测试 Android 演示器时切换上下文



我最近开始在我的 Android 项目中使用 kotlin 协程,但我遇到了一些问题。许多人会称之为代码气味。

我使用的是 MVP 架构,其中协程在我的演示器中启动,如下所示:

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

launchAsync函数是这样实现的(在我的 WorklistPresenter 类扩展的 BasePresenter 类中):

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

这样做的问题是我使用的是依赖于 Android 框架的 UI 协程上下文。我无法在不遇到ViewRootImpl$CalledFromWrongThreadException的情况下将其更改为另一个协程上下文。为了能够对此进行单元测试,我创建了一个具有不同实现的 BasePresenterlaunchAsync的副本:

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

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

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

创建一个提供上下文的接口,具有默认实现:

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

然后你手动或使用注入框架将此(CoroutineContextProvider.Default())注入到表示器构造函数中。然后在代码中使用它提供的上下文: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包装调用它,这将确保所有操作都发生在调用线程(你的测试)中。这里对此进行了解释(请参阅有关"不受限制与受限调度程序"的部分)。

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

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

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

对于其他人使用,这是我最终得到的实现。

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()
}
}
}

您还可以让演示者不知道UI上下文。 相反,演示者应该是无上下文的。 表示器应仅公开suspend函数,并让调用方指定上下文。 然后,当您从视图调用此表示器协程函数时,您可以使用UI上下文launch(UI) { presenter.somethingAsync() }调用它。 这样,在测试演示者时,您可以使用runBlocking { presenter.somethingAsync() }运行测试

最新更新