Код: Выделить всё
// View Model Function
fun initialise() {
viewModelScope.launch(coroutineExceptionHandler) {
val accountDeferred = async(Dispatchers.IO) { accountModel.getAccounts() }
val contentDeferred = async(Dispatchers.IO) { contentModel.getContent() }
val account = accountDeferred.await()
val content = contentDeferred.await()
handleResult(account, content) // viewState is updated
}
}
// Unit Test
// Simplified
class Test {
@get:Rule
val coroutineRule = CoroutineTestRule(StandardTestDispatcher())
@Test
fun `This is the test`() {
runTest{
whenever(accountModel.getAccounts()).thenReturn(
Result.success( getAccountContent() , ReasonStatus.empty()))
whenever(contentModel.getContent()).thenReturn(
Result.success( getContent(), ReasonStatus.empty()))
// start view model
viewmodel = ViewModel(accountModel, contentModel)
runCurrent()
// In debugging mode, the variable viewState is set, before the two jobs in the viewmodel finish
val viewState = viewmodel.viewState.value
// check contents
assertNotEmpty(viewState.accounts)
// always fails since the network calls have not completed
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/786 ... unit-tests
Мобильная версия