【问题标题】:Unit Testing LiveData Value with Coroutines使用协程对 LiveData 值进行单元测试
【发布时间】:2020-05-07 15:42:36
【问题描述】:

我想测试viewmodel的变量是否有repository调用的返回值。这是我第一次使用协程。

这里的问题是我的事件变量在这里返回 null:

Assert.assertEquals(viewModel.event.getOrAwaitValue(), EventGame(games = games))

我的视图模型:

class GamesViewModel(private val repository: GameRepository) : ViewModel(), CoroutineScope {
    override val coroutineContext: CoroutineContext =
        Dispatchers.Main + SupervisorJob()

    private val _event = MutableLiveData<EventGame>()
    val event: LiveData<EventGame> get() = _event


    fun listGames() = this.launch {
        val ej = withContext(Dispatchers.Default) {
            repository.listGames()
        }
        _event.postValue(ej)
    }
}

我的单元测试类

class GamesUnitTest : KoinTest{
    lateinit var viewModel: GameViewModel

    private val g1 = Game(id = 1, data = "01/01/2020 18:35" ...)
    private val g2 = Game(id = 2, data = "01/10/2020 18:35"...)
    private val games = listOf(g1, g2)

    @Mock
    lateinit var repository: GameRepository

    @get:Rule
    var coroutinesTestRule = CoroutinesTestRule()

    @get:Rule
    val instantExecutorRule = InstantTaskExecutorRule()

    @Mock
    lateinit var observer: Observer<EventGame>

    @After
    fun after() {
        stopKoin()
    }

    @Before
    fun before() {
        MockitoAnnotations.initMocks(this)
        viewModel = GameViewModel(repository)
    }

    @Test
    fun testListOfGames() = runBlockingTest{
        Mockito.`when`(repository.listGames()).thenReturn(EventGame(games = games))
        viewModel.event.observeForever(observer)
        viewModel.listGames()
        Assert.assertEquals(viewModel.event.getOrAwaitValue(), EventGame(games = games))

    }
}

--编辑2

我删除了 GlobalScope.launch{}。该事件仍然为空

我不知道如何解决这个问题。

【问题讨论】:

标签: android mockito android-lifecycle android-testing coroutine


【解决方案1】:

我的问题出在我的 Mockito 上。它返回空值。 当我使用 Mockito-Kotlin 时,它运行良好。

来源:Mocked suspend function returns null in Mockito

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2019-12-17
    • 2021-08-09
    • 2018-05-13
    • 2018-04-20
    • 1970-01-01
    • 2018-06-13
    相关资源
    最近更新 更多