为什么带有协程的delay()单元测试失败? [英] Why Unit tests with coroutines delay() fails?

查看:98
本文介绍了为什么带有协程的delay()单元测试失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码我想测试loadSession(),而testLoadSession()是测试方法我有SuccessActivationCodeRepository用于单元测试,而observeForTesting是扩展功能 您可以看到我在单元测试中添加了更长的延迟,但是这并没有为sessionData返回null,我该如何解决?

I have this piece of code I do want to test loadSession() and testLoadSession() is testing method I have SuccessActivationCodeRepository for unit test and observeForTesting is extension function you can see I have added longer delay in the unit test but it doesn't help it return null for sessionData, How can I fix this?

fun loadSession(activationCode: ActivationCode) {
    viewModelScope.launch {
      delay(START_DELAY)
      when (val result = activationCodeRepository.fetchSession(activationCode)) {
        is Response.Success<ISession> -> {
          sessionMutableData.postValue(result.data)
        }
        is Response.Failure -> {
          if (result.message == ERROR_RETRY_ACTIVATION) {
            retryActivationMutableData.postValue(true)
          } else {
            errorMessageMutableData.postValue(ConsumableValue(result.message))
          }
        }
      }
    }
  } 


@Test
  fun testLoadSession() {
    viewModel.activationCodeRepository = SuccessActivationCodeRepository()
    val activationCode = ActivationCode()
    val expectedSession = Session("", "", "")
    viewModel.loadSession(activationCode)
    runBlocking {
      delay(10000L)
    }
    viewModel.sessionData.observeForTesting {
     assertThat(viewModel.sessionData.value?.sessionToken).isEqualTo(expectedSession.sessionToken)
    }
  }

class SuccessActivationCodeRepository : IActivationCodeRepository {
  override suspend fun fetchSession(activationCode: ActivationCode): Response<ISession> {
    return Response.Success(Session())
  }
}

fun <T> LiveData<T>.observeForTesting(block: () -> Unit) {
  val observer = Observer<T> { Unit }
  try {
    observeForever(observer)
    block()
  } finally {
    removeObserver(observer)
  }
}

推荐答案

我添加了coroutinesTestRule.testDispatcher.runBlockingTest {}和advanceTimeBy(20000L),并在loadSession()中将时间设置为大于延迟时间.

I have added coroutinesTestRule.testDispatcher.runBlockingTest {} and advanceTimeBy(20000L) and set time bigger than delay time in loadSession()

 @Test
  fun testLoadSession() {
    viewModel.activationCodeRepository = SuccessActivationCodeRepository()
    val activationCode = ActivationCode()
    val expectedSession = Session()
    coroutinesTestRule.testDispatcher.runBlockingTest {
      viewModel.loadSession(activationCode)
      viewModel.sessionData.observeForTesting {
        advanceTimeBy(20000L)
        assertThat(viewModel.sessionData.value.sessionToken).isEqualTo(expectedSession.sessionToken)
      }
    }
  }```

这篇关于为什么带有协程的delay()单元测试失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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