【发布时间】:2019-07-05 14:46:30
【问题描述】:
我正在努力测试我的演示者,它正在从存储库层调用暂停的函数,如下所示:
override fun viewCreated() {
launch {
val hasPermission = permissionChecker.execute() //suspended function
if (hasPermission) {
foo()
} else {
view.bar()
}
}
presenter也在扩展这个接口:
interface CoroutinePresenter: CoroutineScope {
val job: Job
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
fun stopAllActiveJobs() {
coroutineContext.cancelChildren()
}
而挂起函数定义如下:
suspend fun execute() : Boolean = withContext(Dispatchers.IO) {
return@withContext class.foo()
}
应用程序中的一切都按预期工作,但是当我尝试编写一些单元测试时,我注意到每当我在 launch 中调用这段代码时,线程都会切换,但测试不会等待执行。这是测试的实现:
@Test
fun `Test of Suspended Function`() = runBlocking {
presenter.viewCreated()
then(view).should().bar()
...
}
我还添加了用于测试kotlinx-coroutines-test 的建议库,但结果仍然与它相同。我还尝试遵循this 的建议并实施类似this 的方法,但仍然没有运气。
我认为问题是在演示者中调用 launch 时实际创建另一个线程并且测试实际上并不知道如何等待它。我还尝试返回一个 Job 并调用 job.join(),但它以 NullPointerException 失败。
希望你们能帮助我。
【问题讨论】:
标签: android unit-testing kotlin android-testing kotlin-coroutines