Skip to content

Instantly share code, notes, and snippets.

View CostaFot's full-sized avatar
🍦

Costa Fotiadis CostaFot

🍦
View GitHub Profile
class RedditRepository(private val dispatcherProvider: DispatcherProvider) {
suspend fun getPost(): State.Post {
return withContext(dispatcherProvider.io) {
// ...imaginary operation that will take a while
// ..
State.Post("I hope this post gets me karma points") // return on completion
}
}
}
@ExperimentalCoroutinesApi
class CoroutineTestRule(
val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()
) : TestWatcher() {
val testDispatcherProvider = object : DispatcherProvider {
override val io: CoroutineDispatcher = testDispatcher
override val ui: CoroutineDispatcher = testDispatcher
override val default: CoroutineDispatcher = testDispatcher
override val unconfined: CoroutineDispatcher = testDispatcher
dependencies {
// .. other dependencies
// ..
// testing dependencies
testImplementation 'androidx.test.ext:junit:1.1.2-alpha03'
testImplementation 'org.mockito:mockito-core:3.0.0'
testImplementation 'com.nhaarman.mockitokotlin2:mockito-kotlin:2.1.0'
testImplementation 'org.mockito:mockito-inline:3.0.0'
testImplementation 'org.amshove.kluent:kluent:1.51'
@ExperimentalCoroutinesApi
class RedditRepositoryTest {
@get:Rule
val coroutineTestRule = CoroutineTestRule()
private lateinit var redditRepository: RedditRepository
@Before
fun setUp() {
@CostaFot
CostaFot / Test.kt
Last active February 7, 2020 00:34
@Test
fun `getPost actually returns the post I am expecting`() {
// run the test on the testDispatcher provided by the coroutineTestRule
coroutineTestRule.testDispatcher.runBlockingTest {
// Given
val expectedPost: State.Post = State.Post("I hope this post gets me karma points")
// When
val actualPost: State.Post = redditRepository.getPost()
// Then
assertEquals(expectedPost, actualPost)
@CostaFot
CostaFot / ext.kt
Last active January 19, 2020 21:23
@ExperimentalCoroutinesApi
fun CoroutineTestRule.runBlockingTest(block: suspend TestCoroutineScope.() -> Unit) {
testDispatcher.runBlockingTest(block)
}
interface DispatcherProvider {
val io: CoroutineDispatcher
val ui: CoroutineDispatcher
val default: CoroutineDispatcher
val unconfined: CoroutineDispatcher
}
class LifeCycleTestOwner : LifecycleOwner {
private val registry = LifecycleRegistry(this)
override fun getLifecycle(): Lifecycle {
return registry
}
fun onCreate() {
registry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
@ExperimentalCoroutinesApi
class ViewModelTest {
@get:Rule
var coroutinesTestRule = TestCoroutineDispatcherRule()
@get:Rule
var rule: TestRule = InstantTaskExecutorRule()
private val stateObserver: Observer<State> = mock()
class PostViewModel(private val redditRepository: RedditRepository) : ViewModel() {
val stateData = MutableLiveData<State>()
fun getRedditPost() {
viewModelScope.launch {
stateData.value = State.Loading
val post: State.Post = redditRepository.getPost()
stateData.value = post
}