如何在Kotlin中使用ViewModel测试协程? [英] How to test Coroutine with ViewModel in Kotlin?

查看:264
本文介绍了如何在Kotlin中使用ViewModel测试协程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法测试我的方法,感觉它没有到达uiScope.launch块内部,并且我发布了我要测试的viewModel方法,并且fetchActivationCodeWithDuration是暂停功能.底部是我的测试班

I could not test my method it feels it doesn't reach inside uiScope.launch block and I have posted my viewModel method which I am trying to test and fetchActivationCodeWithDuration is suspend function. and in the bottom is my test class

我收到此消息

java.lang.AssertionError: 
    Expected :ActivationCode(code=111111, expires=2019-05-23T10:03:50.614Z, duration=815960) Actual   :null

protected val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)

fun loadActivationCode() {
    uiScope.launch {
        progressMessageMutableData.postValue(true)
        when (val result = activationCodeRepository.fetchActivationCodeWithDuration()) {
            is Resource.Success<ActivationCode> -> {
                progressMessageMutableData.postValue(false)
                activationMutableData.postValue(result.data)
            }
            is Resource.Failure -> {
                progressMessageMutableData.postValue(false)
                errorMessageMutableData.postValue(result.message)
            }
        }
    }

suspend fun fetchActivationCodeWithDuration(): Resource<ActivationCode> {}

这是我的考试班

@ExperimentalCoroutinesApi
@RunWith(JUnit4::class)
class ActivationViewModelTest {
    @get:Rule
    val instantTaskExecutorRule = InstantTaskExecutorRule()

    @UseExperimental(ObsoleteCoroutinesApi::class)
    private val mainThreadSurrogate = newSingleThreadContext("UI thread")
    private lateinit var viewModel: ActivationViewModel
    private lateinit var serverTimeFetcher: IServerTimeFetcher
    private lateinit var activationCodeRepository: ActivationRepositoryCode

    @Before
    fun setup() {
        viewModel = ActivationViewModel()
        Dispatchers.setMain(mainThreadSurrogate)
        activationCodeRepository = mock(ActivationRepositoryCode::class.java)
        viewModel.activationCodeRepository = activationCodeRepository
    }

    @After
    fun tearDown() {
        Dispatchers.resetMain() // reset main dispatcher to the original Main dispatcher
        mainThreadSurrogate.close()
    }

    @Test
    fun whenSuccessMenuLoad_loadActivationCode() {
        runBlockingTest {
            Mockito.`when`(activationCodeRepository.fetchActivationCodeWithDuration()).
              thenReturn(Resource.Success(ActivationCode(code = "111111", expires = "2019-05-23T10:03:50.614Z", duration = 815960L)))
            viewModel.loadActivationCode()
            val expected = ActivationCode(code = "111111", expires = "2019-05-23T10:03:50.614Z", duration = 815960L)
            val actual = viewModel.activationData.value
            Assert.assertEquals(expected, actual)
        }
    }
}

推荐答案

更好的方法是将coroutineDispatcher传递给viewModel,因此您可以在测试中传递测试分派器.所以你应该有:

Better approach is to pass coroutineDispatcher to viewModel, so you can pass test dispatcher in your tests. so you should have :

class ActivationViewModel(val dispatcher:CoroutineDispatcher){}

在测试中,您可以像这样初始化viewModel:

and in your test you can init viewModel like this :

val dispatcher=Dispatchers.Unconfined
val viewModelInTest=ActivationViewModel(dispatcher)

问题将得到解决..

这篇关于如何在Kotlin中使用ViewModel测试协程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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