如何在Kotlin中使用ViewModel测试协程?

时间:2019-05-23 16:13:05

标签: android unit-testing kotlin kotlin-coroutines

我无法测试我的方法,感觉它没有到达uiScope.launch块内,并且我发布了我正在尝试测试的viewModel方法,并且fetchActivationCodeWithDuration是暂停函数。底部是我的测试班

我收到此消息

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)
        }
    }
}

1 个答案:

答案 0 :(得分:0)

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

class ActivationViewModel(val dispatcher:CoroutineDispatcher){}

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

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

问题将得到解决。.