Skip to content

Instantly share code, notes, and snippets.

@abdulhafizramadan-ittp
Last active May 31, 2022 03:15
Show Gist options
  • Select an option

  • Save abdulhafizramadan-ittp/0b0c12992aceeab8c7667e651ecee9d9 to your computer and use it in GitHub Desktop.

Select an option

Save abdulhafizramadan-ittp/0b0c12992aceeab8c7667e651ecee9d9 to your computer and use it in GitHub Desktop.
Android | Testing Coroutines
plugins {
...
}
android {
...
}
dependencies {
...
// KotlinX Coroutines for Testing
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.2'
...
}
package com.ahr.newsapp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestWatcher
import org.junit.runner.Description
@ExperimentalCoroutinesApi
class MainDispatcherRule(
private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher()
) : TestWatcher() {
override fun starting(description: Description) {
Dispatchers.setMain(testDispatcher)
}
override fun finished(description: Description) {
Dispatchers.resetMain()
}
}
package com.ahr.newsapp.ui.detail
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.MutableLiveData
import com.dicoding.newsapp.DataDummy
import com.dicoding.newsapp.MainDispatcherRule
import com.dicoding.newsapp.data.NewsRepository
import com.dicoding.newsapp.getOrAwaitValue
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnitRunner
@ExperimentalCoroutinesApi
@RunWith(MockitoJUnitRunner::class)
class NewsDetailViewModelTest {
...
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
...
@Test
fun `when bookmarkStatus false should call saveNews`() = runTest {
...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment