Rak
06/25/2021, 4:56 AMRak
06/25/2021, 4:59 AM@ExperimentalCoroutinesApi
@ExperimentalTime
internal class IntegrationTest : BaseViewModelTest() {
@Test
fun `my first test`() = coroutineDispatcher.runBlockingTest {
val viewModel = MyViewModel(MyRepo(), coroutineDispatcher)
pauseDispatcher()
viewModel.handleIntent()
viewModel.state.test {
val first = expectItem() as <http://ViewState.Info|ViewState.Info>
assertEquals(<http://ViewState.Info::class|ViewState.Info::class>, first::class)
cancelAndConsumeRemainingEvents()
}
resumeDispatcher()
}
}
class MyViewModel(
private val repo: MyRepo,
private val dispatcher: CoroutineDispatcher
) : ViewModel() {
private val _state = MutableStateFlow<ViewState>(ViewState.Loading)
val state: StateFlow<ViewState>
get() = _state
fun handleIntent() {
viewModelScope.launch() {
withContext(dispatcher) {
val name = repo.getUser()
_state.emit(<http://ViewState.Info|ViewState.Info>(name))
}
}
}
}
sealed class ViewState {
object Loading : ViewState()
data class Info(val name: String) : ViewState()
}
class MyRepo {
suspend fun getUser(): String {
delay(1000L)
return "John"
}
}