Я разрабатываю новостное приложение и хочу правильно протестировать свои Kotlin сопрограммы с MainViewModel, Livedata и репозиторием. Я написал тестовый журнал c уже здесь
class MainViewModelTest {
private val sportNewsApi: SportNewsInterface? = null
private val testDispatcher = TestCoroutineDispatcher()
private val testScope = TestCoroutineScope(testDispatcher)
@Before
fun before() {
Dispatchers.setMain(testDispatcher)
}
@After
fun after() {
Dispatchers.resetMain()
testScope.cleanupTestCoroutines()
}
@Test
fun testYourFunc() = testScope.runBlockingTest {
val mockRepo = mock<NewsRepository> {
onBlocking { sportNewsApi("") } doReturn Response.success(listOf())
}
val viewModel = MainViewModel(mockRepo)
val result = viewModel.newsRepository.refresh()
assertEquals(viewModel, result)
}
}
ниже моего MainViewModel.kt
@Suppress("UNCHECKED_CAST")
class MainViewModel(val newsRepository: NewsRepository) : ViewModel(), CoroutineScope {
// Coroutine's background job
val job = Job()
// Define default thread for Coroutine as Main and add job
override val coroutineContext: CoroutineContext = Dispatchers.Main + job
private val _showLoading = MutableLiveData<Boolean>()
private val _sportList = MutableLiveData<Results>()
val showLoading: LiveData<Boolean>
get() = _showLoading
val sportList: LiveData<Results>
get() = _sportList
fun loadNews() {
// Show progressBar during the operation on the MAIN (default) thread
_showLoading.value = true
// launch the Coroutine
launch {
// Switching from MAIN to IO thread for API operation
// Update our data list with the new one from API
val result = newsRepository.refresh()
_sportList.value = result
_showLoading.value = false
}
}
override fun onCleared() {
job.cancel()
}
}
below NewsRepository
class NewsRepository (частный val sportNewsApi: SportNewsInterface, частный val sportNewsDao: SportNewsDao) {
val data = sportNewsDao.getAllData()
suspend fun refresh() = withContext(Dispatchers.IO) {
val articles = sportNewsApi.getNewsAsync().body()?.articles
if (articles != null) {
sportNewsDao.addAll(articles)
Results.Success(articles)
} else {
Results.Failure("MyError")
}
}
}