小编kap*_*inz的帖子

使用协程测试简单的加载+获取流程,就像使用 StandardTestDispatcher 进行 Android 仪器测试一样

我想在 Android 中测试以下非常常见的用例作为仪器测试:

  • 单击按钮时,我的 ViewModel 中会调用 fetch() 函数
  • 该函数告诉视图显示加载覆盖
  • 它在协程中执行提取
  • 获取结果后,它让视图知道显示结果

这是我的 Viewmodel 中的函数:

fun fetch() {
    _loading.value = true //loading is shown
    viewModelScope.launch {
        val results = fetchUseCase() //suspend function
        _result.postValue(results)
        _loading.postValue(false) //loading is not displayed
    }
}
Run Code Online (Sandbox Code Playgroud)

这是根据此 CodeLab https://developer.android.com/codelabs/advanced-android-kotlin-training-testing-survey#4进行的测试:

@HiltAndroidTest
@UninstallModules(CoroutinesDispatcherModule::class)
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTestJunit4Deprecated {

@get:Rule
var hiltRule = HiltAndroidRule(this)

@ExperimentalCoroutinesApi
@get:Rule
var mainCoroutineRule = MainCoroutineRule()

@Before
fun setup() {
    ActivityScenario.launch(HomeScreenActivity::class.java)
}

@ExperimentalCoroutinesApi
@Test
fun fetchTest() {

    //pausing the long running tasks
    mainCoroutineRule.pauseDispatcher()

    //When clicking the …
Run Code Online (Sandbox Code Playgroud)

android ui-testing dispatcher coroutine kotlin

5
推荐指数
0
解决办法
624
查看次数

标签 统计

android ×1

coroutine ×1

dispatcher ×1

kotlin ×1

ui-testing ×1