[英]Unit Testing LiveData Value with Coroutines
I want to test if the viewmodel's variable has the return value of the repository call.我想测试视图模型的变量是否具有存储库调用的返回值。 It is my first time using Coroutines.
这是我第一次使用协程。
The problem here is that my event variable is returning null here:这里的问题是我的事件变量在这里返回 null:
Assert.assertEquals(viewModel.event.getOrAwaitValue(), EventGame(games = games))
Assert.assertEquals(viewModel.event.getOrAwaitValue(),EventGame(游戏=游戏))
My viewModel:我的视图模型:
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)
}
}
My unit test class我的单元测试课
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))
}
}
--Edit2 --编辑2
I removed the GlobalScope.launch{}.我删除了 GlobalScope.launch{}。 The event is still null
该事件仍然为空
I'm not sure how to fix that.我不确定如何解决这个问题。
My problem was in my Mockito.我的问题出在我的 Mockito 上。 It was returning null.
它返回空值。 When I used Mockito-Kotlin it worked fine.
当我使用 Mockito-Kotlin 时,它运行良好。
source: Mocked suspend function returns null in Mockito来源: 模拟挂起函数在 Mockito 中返回 null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.