使用viewModelScope

时间:2019-09-26 10:48:49

标签: kotlin kotlin-coroutines

我想测试ViewModel的一种收集Flow的方法。在收集器内部,对LiveData对象进行了突变,我想最后检查一下。大致是这样的设置:

//Outside viewmodel
val f = flow { emit("Test") }.flowOn(Dispatchers.IO)

//Inside viewmodel
val liveData = MutableLiveData<String>()

fun action() {
    viewModelScope.launch { privateAction() }
}

suspend fun privateAction() {
    f.collect {
        liveData.value = it
    }
}

现在我在单元测试中调用action()方法时,测试将在收集流之前完成。测试结果如下:

@Test
fun example() = runBlockingTest {
    viewModel.action()
    assertEquals(viewModel.liveData.value, "Test")
}

我正在通过此Junit5扩展以及LiveData的即时执行程序扩展来使用TestCoroutineDispatcher:

    class TestCoroutineDispatcherExtension : BeforeEachCallback, AfterEachCallback, ParameterResolver {
    @SuppressLint("NewApi") // Only used in unit tests
    override fun supportsParameter(parameterContext: ParameterContext?, extensionContext: ExtensionContext?): Boolean {
        return parameterContext?.parameter?.type === testDispatcher.javaClass
    }

    override fun resolveParameter(parameterContext: ParameterContext?, extensionContext: ExtensionContext?): Any {
        return testDispatcher
    }

    private val testDispatcher = TestCoroutineDispatcher()

    override fun beforeEach(context: ExtensionContext?) {
        Dispatchers.setMain(testDispatcher)
    }

    override fun afterEach(context: ExtensionContext?) {
        Dispatchers.resetMain()
        testDispatcher.cleanupTestCoroutines()
    }
}

    class InstantExecutorExtension : BeforeEachCallback, AfterEachCallback {
    override fun beforeEach(context: ExtensionContext?) {
        ArchTaskExecutor.getInstance()
            .setDelegate(object : TaskExecutor() {
                override fun executeOnDiskIO(runnable: Runnable) = runnable.run()
                override fun postToMainThread(runnable: Runnable) = runnable.run()
                override fun isMainThread(): Boolean = true
            })
    }

    override fun afterEach(context: ExtensionContext?) {
        ArchTaskExecutor.getInstance().setDelegate(null)
    }
}

2 个答案:

答案 0 :(得分:0)

您可以尝试

fun action() = viewModelScope.launch { privateAction() }

suspend fun privateAction() {
    f.collect {
        liveData.value = it
    }
}

@Test
fun example() = runBlockingTest {
    viewModel.action().join()
    assertEquals(viewModel.liveData.value, "Test")
}

fun action() {
    viewModelScope.launch { privateAction()
}

suspend fun privateAction() {
    f.collect {
        liveData.value = it
    }
}

@Test
fun example() = runBlockingTest {
    viewModel.action()
    viewModel.viewModelScope.coroutineContext[Job]!!.join()
    assertEquals(viewModel.liveData.value, "Test")
}

您也可以尝试

suspend fun <T> LiveData<T>.awaitValue(): T? {
    return suspendCoroutine { cont ->
        val observer = object : Observer<T> {
            override fun onChanged(t: T?) {
                removeObserver(this)
                cont.resume(t)
            }
        }
        observeForever(observer)
    }
}

@Test
fun example() = runBlockingTest {
    viewModel.action()
    assertEquals(viewModel.liveData.awaitValue(), "Test")
}

答案 1 :(得分:0)

所以我最终要做的只是将Dispatcher传递给viewmodel构造函数:

class MyViewModel(..., private val dispatcher = Dispatchers.Main)

然后像这样使用它:

viewModelScope.launch(dispatcher) {}

因此,当我在测试中使用ViewModel实例化TestCoroutineDispatcher并延长时间,使用testCoroutineDispatcher.runBlockingTest {}等时,可以覆盖此设置。