ViewModel单元使用LiveData,Coroutines和MockK测试多个视图状态 [英] ViewModel Unit testing multiple view states with LiveData, Coroutines and MockK

查看:380
本文介绍了ViewModel单元使用LiveData,Coroutines和MockK测试多个视图状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ViewModel中有一个具有2个状态的函数,第一个状态始终是LOADING,第二个状态取决于api或db交互的结果.

I have a function in ViewModel with 2 states, first state is always LOADING, second state depends on result of api or db interactions.

这是功能

fun getPostWithSuspend() {

    myCoroutineScope.launch {

        // Set current state to LOADING
        _postStateWithSuspend.value = ViewState(LOADING)

        val result = postsUseCase.getPosts()

        // Check and assign result to UI
        val resultViewState = if (result.status == SUCCESS) {
            ViewState(SUCCESS, data = result.data?.get(0)?.title)
        } else {
            ViewState(ERROR, error = result.error)
        }

        _postStateWithSuspend.value = resultViewState
    }
}

而且没有错误,测试可以很好地检查ERROR或SUCCESS的最终结果

And no error, test works fine for checking final result of ERROR or SUCCESS

   @Test
    fun `Given DataResult Error returned from useCase, should result error`() =
        testCoroutineRule.runBlockingTest {

            // GIVEN
            coEvery {
                useCase.getPosts()
            } returns DataResult.Error(Exception("Network error occurred."))

            // WHEN
            viewModel.getPostWithSuspend()

            // THEN
            val expected = viewModel.postStateWithSuspend.getOrAwaitMultipleValues(dataCount = 2)

//            Truth.assertThat("Network error occurred.").isEqualTo(expected?.error?.message)
//            Truth.assertThat(expected?.error).isInstanceOf(Exception::class.java)
            coVerify(atMost = 1) { useCase.getPosts() }
        }

但是我找不到测试LOADING状态是否发生的方法,因此我将现有扩展功能修改为

But i couldn't find a way to test whether LOADING state has occurred or not, so i modified existing extension function to

fun <T> LiveData<T>.getOrAwaitMultipleValues(
    time: Long = 2,
    dataCount: Int = 1,
    timeUnit: TimeUnit = TimeUnit.SECONDS,
    afterObserve: () -> Unit = {}
): List<T?> {

    val data = mutableListOf<T?>()
    val latch = CountDownLatch(dataCount)

    val observer = object : Observer<T> {
        override fun onChanged(o: T?) {
            data.add(o)
            latch.countDown()
            this@getOrAwaitMultipleValues.removeObserver(this)
        }
    }
    this.observeForever(observer)

    afterObserve.invoke()

    // Don't wait indefinitely if the LiveData is not set.
    if (!latch.await(time, timeUnit)) {
        this.removeObserver(observer)
        throw TimeoutException("LiveData value was never set.")
    }

    @Suppress("UNCHECKED_CAST")
    return data.toList()
}

在LiveData更改时将数据添加到列表中并将状态存储在该列表中,但是 它永远不会返回LOADING状态,因为它发生在观察开始之前.有没有一种方法可以测试LiveData的多个值?

To add data to a list when LiveData changes and store states in that list but it never returns LOADING state because it happens before observe starts. Is there a way to test multiple values of LiveData?

推荐答案

使用 mockk ,您可以捕获值并将其存储在列表中,然后检查值按订单.

Using mockk you can capture the values and store it in the list, then you check the values by order.

    //create mockk object
    val observer = mockk<Observer<AnyObject>>()

    //create slot
    val slot = slot<AnyObject>()

    //create list to store values
    val list = arrayListOf<AnyObject>()

    //start observing
    viewModel.postStateWithSuspend.observeForever(observer)


    //capture value on every call
    every { observer.onChanged(capture(slot)) } answers {

        //store captured value
        list.add(slot.captured)
    }

    viewModel.getPostWithSuspend()
    
    //assert your values here
    

这篇关于ViewModel单元使用LiveData,Coroutines和MockK测试多个视图状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆