众所周知,viewModelScope的默认调度程序是并行执行的。如何使viewModelScope等待单元测试中的suspend函数。在我的代码中,我想从repository.getData()获得结果,以便我的断言通过。现在,我没有准时得到结果。

class MainViewModel(private val repository: Repository,
                     private val dispatcher: CoroutineDispatcherProvider) : ViewModel() {

    private val viewState = MutableLiveData<Results<Data>>()
    fun getViewState() : LiveData<Results<Data>> = viewState



    fun getData(query: search) {
        viewState.value = Loading
        viewModelScope.launch(dispatcher.main()) {
            val results = repository.getData(query) //need to wait for this
            when(results){
                    is Success -> {
                        viewState.value = Success(results.data)
                    }
                    is Error -> viewState.value = Error(“Error”)
                }
        }

MainViewModelTest:
 Class MainViewModelTest {

    @get:Rule
    val instantExecutorRule = InstantTaskExecutorRule()

    @get:Rule
    val coroutineTestRule = CoroutineTestRule()


    @Test
    fun `test get data`() = coroutineTestRule.testCoroutineDispatcher.runBlockingTest {
        coEvery{repository.getData(“query”)} returns Success(Data)

        var observer:Observer<Results<Data>> = mock()

        viewModel.getViewState().observeForever(observer)

        viewModel.getData(“query”)

          assertEquals(Loading, state)
          assertEquals(resultSuccess, state)

       }

    }

最佳答案

我认为您应该使用observer.onChanged()进行断言和验证。否则我看不到问题。

val successResult = Result.Success(Data)
coEvery{repository.getData(“query”)} returns successResult

verify { observer.onChanged(Result.Loading) }
verify { observer.onChanged(successResult) }

关于android - 如何在单元测试中使viewModelScope等待挂起功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60938614/

10-09 15:25