Share
Embed
Unit Testing Kotlin Channels & Flows - Android Summit
Unit testing Channels and Flows can be a challenge as they are fairly new. In this talk, I will share with you how to implement and test practical examples from my experience. These examples are testing delays, retries, and errors. I'll also share testing more complex examples such as polling. For each use case, we'll look at how to use features in the coroutines library such as runBlockingTest and TestCoroutineDispatcher. From my journey of using and testing Flows in production, I'll share the challenges I experienced.
Mohit S
October 09, 2020
Annual Pro sale · Save $30
Have presentations of your own?
Share with private links, password protection, and more control over your work.
Transcript
215 slides
-
Unit Testing Channels & Flows • Run Blocking Test •
Flow Test Cases • Flow Assertions with Turbine • View Model Testing • Testing in Coroutines Lib -
Flow Test Cases • Collection • Run on Dispatcher •
Errors • Retries Fail • Retry Succeeds -
class UsersRepository(val apiService: ApiService) { fun getUsers(): Flow<String> { return
apiService.getUsers() .filter { it.location "== "NYC" } .map { it.name } } } -
class UsersRepository(val apiService: ApiService) { fun getUsers(): Flow<String> { return
apiService.getUsers() .filter { it.location "== "NYC" } .map { it.name } } } -
class UsersRepository(val apiService: ApiService) { fun getUsers(): Flow<String> { return
apiService.getUsers() .filter { it.location "== "NYC" } .map { it.name } } } -
class UsersRepository(val apiService: ApiService) { fun getUsers(): Flow<String> { return
apiService.getUsers() .filter { it.location "== "NYC" } .map { it.name } } } Flow of Users -
class UsersRepository(val apiService: ApiService) { fun getUsers(): Flow<String> { return
apiService.getUsers() .filter { it.location "== "NYC" } .map { it.name } } } Filter users -
class UsersRepository(val apiService: ApiService) { fun getUsers(): Flow<String> { return
apiService.getUsers() .filter { it.location "== "NYC" } .map { it.name } } } Map user name -
class UsersRepository(val apiService: ApiService) { fun getUsers(): Flow<String> { return
apiService.getUsers() .filter { it.location "== "NYC" } .map { it.name } } } How do we test this Flow? -
Kotlin/kotlinx.coroutines Code ! Issues Pull Requests kotlinx-coroutines-core 2,093 commits 4c28f942
13 hours ago Kotlinx-coroutines-debug Kotlinx-coroutines-test reactive js benchmarks -
Kotlin/kotlinx.coroutines Code ! Issues Pull Requests kotlinx-coroutines-core 2,093 commits 4c28f942
13 hours ago Kotlinx-coroutines-debug Kotlinx-coroutines-test reactive js benchmarks Testing Module -
Kotlin/kotlinx.coroutines Code ! Issues Pull Requests README.md Module Kotlin-coroutines-test Test
utilities for kotlinx.coroutines dependencies { testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.9' } -
@Test fun `should get users`() = runBlockingTest { } Test
Scope + Test Dispatcher -
@Test fun `should get users`() = runBlockingTest { } Test
Scope + Test Dispatcher What is executed in this coroutine? -
@Test fun `should get users`() = runBlockingTest { } Test
Scope + Test Dispatcher -
@Test fun `should get users`() = runBlockingTest { } Test
Scope + Test Dispatcher -
fun runBlockingTest(testBody) { val scope = TestCoroutineScope(safeContext) val deferred =
scope.async { scope.testBody() } deferred.getCompletionExceptionOrNull()"?.let { throw it } scope.cleanupTestCoroutines() if (hasActiveJobs()) { throw UncompletedCoroutinesError("Test finished with active jobs: $endingJobs") } } Our test to run -
fun runBlockingTest(testBody) { val scope = TestCoroutineScope(safeContext) val deferred =
scope.async { scope.testBody() } deferred.getCompletionExceptionOrNull()"?.let { throw it } scope.cleanupTestCoroutines() if (hasActiveJobs()) { throw UncompletedCoroutinesError("Test finished with active jobs: $endingJobs") } } Test Coroutine Scope -
fun runBlockingTest(testBody) { val scope = TestCoroutineScope(safeContext) val deferred =
scope.async { scope.testBody() } deferred.getCompletionExceptionOrNull()"?.let { throw it } scope.cleanupTestCoroutines() if (hasActiveJobs()) { throw UncompletedCoroutinesError("Test finished with active jobs: $endingJobs") } } Wrap your test in Deferred -
fun runBlockingTest(testBody) { val scope = TestCoroutineScope(safeContext) val deferred =
scope.async { scope.testBody() } deferred.getCompletionExceptionOrNull()"?.let { throw it } scope.cleanupTestCoroutines() if (hasActiveJobs()) { throw UncompletedCoroutinesError("Test finished with active jobs: $endingJobs") } } Run your test! -
fun runBlockingTest(testBody) { val scope = TestCoroutineScope(safeContext) val deferred =
scope.async { scope.testBody() } deferred.getCompletionExceptionOrNull()"?.let { throw it } scope.cleanupTestCoroutines() if (hasActiveJobs()) { throw UncompletedCoroutinesError("Test finished with active jobs: $endingJobs") } } Cancel all Jobs in test -
fun runBlockingTest(testBody) { val scope = TestCoroutineScope(safeContext) val deferred =
scope.async { scope.testBody() } deferred.getCompletionExceptionOrNull()"?.let { throw it } scope.cleanupTestCoroutines() if (hasActiveJobs()) { throw UncompletedCoroutinesError("Test finished with active jobs: $endingJobs") } } Fail on active coroutines -
fun runBlockingTest(testBody) { val scope = TestCoroutineScope(safeContext) val deferred =
scope.async { scope.testBody() } deferred.getCompletionExceptionOrNull()"?.let { throw it } scope.cleanupTestCoroutines() if (activeJobs()).isNotEmpty()) { throw UncompletedCoroutinesError("Test finished with active jobs") } } Setup Run Test Cleanup -
class UsersRepository(val apiService: ApiService) { fun getUsers(): Flow<String> { return
apiService.getUsers() .filter { it.location "== "NYC" } .map { it.name } } } How do we mock service? -
class UsersRepository(val apiService: ApiService) { fun getUsers(): Flow<String> { return
apiService.getUsers() .filter { it.location "== "NYC" } .map { it.name } } } Mock or Create fake -
nhaarman/mockito-kotlin Code ! Issues Pull Requests Mockito-Kotlin A small library
that provides helper functions to work with Mockito in Kotlin. maven central 2.2.0 -
val apiService = mock<ApiService> { on { getUsers() } doReturn
users.asFlow() } @Test fun `should get users`() = runBlockingTest { } Mock API Service -
val apiService = mock<ApiService> { on { getUsers() } doReturn
users.asFlow() } @Test fun `should get users`() = runBlockingTest { } Return a Flow of users -
val apiService = mock<ApiService> { on { getUsers() } doReturn
users.asFlow() } @Test fun `should get users`() = runBlockingTest { } val users = listOf( User(1, "User 1", "NJ"), User(2, "User 2", "NYC"), User(3, "User 3", "CA"), User(4, "User 4", "NJ"), User(5, "User 5", "NYC") ) -
val apiService = mock<ApiService> { on { getUsers() } doReturn
users.asFlow() } val usersRepository = UsersRepository(apiService) fun `should get users`() = runBlockingTest { } Inject mock into Repo -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().toList() assertEquals(users, listOf("User 2", "User 5")) } Collect Flow into List -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().toList() assertEquals(users, listOf("User 2", "User 5")) } Assert on returned user names -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().toList() assertEquals(users, listOf("User 2", "User 5")) } Is there a better way to collect from Flows in test? -
cashApp/turbine Code ! Issues Pull Requests Turbine Small testing library
for kotlinx.coroutines Flow. testImplementation 'app.cash.turbine:turbine:0.2.1' -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().test { expectItem() shouldBe "User 2" expectItem() shouldBe "User 5" expectComplete() } } Library has test extension on Flow -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().test { expectItem() shouldBe "User 2" expectItem() shouldBe "User 5" expectComplete() } } Read from item from Flow -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().test { expectItem() shouldBe "User 2" expectItem() shouldBe "User 5" expectComplete() } } Assertion -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().test { expectItem() shouldBe "User 2" expectItem() shouldBe "User 5" expectComplete() } } Use expectItem to fetch each item -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().test { expectItem() shouldBe "User 2" expectItem() shouldBe "User 5" expectComplete() } } Verify no more emission by Flow -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().test { expectItem() shouldBe "User 2" expectItem() shouldBe "User 5" expectComplete() } } What if flow emitted more items than 2? -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().test { expectItem() shouldBe "User 2" expectItem() shouldBe "User 5" expectComplete() } } UserRepoTests.kt Run: UserRepoTest should get users app.cash.turbine.AssertionError: Expected complete but found Item(User 6) One more item in Flow -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().test { expectItem() shouldBe "User 2" expectItem() shouldBe "User 5" expectItem() shouldBe "User 6” expectComplete() } } UserRepoTests.kt Run: UserRepoTest should get users Add expect item -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().test { expectItem() shouldBe "User 2" expectItem() shouldBe "User 5" expectComplete() } } What if we didn’t expect complete? -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().test { expectItem() shouldBe "User 2" expectItem() shouldBe "User 5" } } UserRepoTests.kt Run: UserRepoTest should get users app.cash.turbine.AssertionError: Unconsumed events found: - Complete Need to assert flow finished -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().test { expectItem() shouldBe "User 2" expectItem() shouldBe "User 5" expectComplete() } } UserRepoTests.kt Run: should get users UserRepoTest -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().test { expectItem() shouldBe "User 2" expectItem() shouldBe "User 5" expectComplete() } } UserRepoTests.kt Run: should get users UserRepoTest How does this work? -
Channel (Unlimited) sealed class Event<out T> { object Complete data
class Error(""...) data class Item(val value: T) } Event How Turbine Works -
interface FlowTurbine<T> { val timeout: Duration fun expectNoEvents() suspend fun
expectItem(): T fun expectError(): Throwable suspend fun expectComplete() } API to verify emissions How Turbine Works -
interface FlowTurbine<T> { val timeout: Duration fun expectNoEvents() suspend fun
expectItem(): T fun expectError(): Throwable suspend fun expectComplete() } Verify duration of emission How Turbine Works -
interface FlowTurbine<T> { val timeout: Duration fun expectNoEvents() suspend fun
expectItem(): T fun expectError(): Throwable suspend fun expectComplete() } Verify no emissions How Turbine Works -
interface FlowTurbine<T> { val timeout: Duration fun expectNoEvents() suspend fun
expectItem(): T fun expectError(): Throwable suspend fun expectComplete() } Verify item emitted How Turbine Works -
interface FlowTurbine<T> { val timeout: Duration fun expectNoEvents() suspend fun
expectItem(): T fun expectError(): Throwable suspend fun expectComplete() } Verify error occurred How Turbine Works -
interface FlowTurbine<T> { val timeout: Duration fun expectNoEvents() suspend fun
expectItem(): T fun expectError(): Throwable suspend fun expectComplete() } Verify all items emitted How Turbine Works -
interface FlowTurbine<T> { val timeout: Duration fun expectNoEvents() suspend fun
expectItem(): T fun expectError(): Throwable suspend fun expectComplete() } How Turbine Works -
How Turbine Works suspend fun <T> Flow<T>.test(""...) { coroutineScope {
} Create a coroutine -
How Turbine Works suspend fun <T> Flow<T>.test(""...) { coroutineScope {
val events = Channel<Event<T">>(UNLIMITED) } Channel of events -
How Turbine Works suspend fun <T> Flow<T>.test(""...) { coroutineScope {
val events = Channel<Event<T">>(UNLIMITED) launch { } } -
How Turbine Works suspend fun <T> Flow<T>.test(""...) { coroutineScope {
val events = Channel<Event<T">>(UNLIMITED) launch { collect { item "-> events.send(Event.Item(item)) } } Store emissions -
How Turbine Works suspend fun <T> Flow<T>.test(""...) { coroutineScope {
val events = Channel<Event<T">>(UNLIMITED) launch { try { collect { ""... } } catch { events.send(Event.Error) } } Send error to Channel -
How Turbine Works suspend fun <T> Flow<T>.test( validate: suspend FlowTurbine<T>.()
"-> Unit ) { coroutineScope { val events = Channel<Event<T">>(UNLIMITED) launch { try { collect { ""... } } catch { events.send(Event.Error) Lambda block -
How Turbine Works suspend fun <T> Flow<T>.test( validate: suspend FlowTurbine<T>.()
"-> Unit ) { coroutineScope { val events = Channel<Event<T">>(UNLIMITED) launch { try { collect { ""... } } catch { events.send(Event.Error) API -
@Test fun `should get users`() = runBlockingTest { val users
= usersRepository.getUsers().test { expectItem() shouldBe "User 2" expectItem() shouldBe "User 5" expectComplete() } } Read emissions with API -
Flow Test Cases • Collection • Run on Dispatcher •
Errors • Retries Fail • Retry Succeeds -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } Run on Dispatcher -
class UsersRepository( val apiService: ApiService, val dispatcher: CoroutineDispatcher ) {
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC" } .map { Result.success(it.name) } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Inject Dispatcher -
class UsersRepository( val apiService: ApiService, val dispatcher: CoroutineDispatcher ) {
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC" } .map { Result.success(it.name) } .flowOn(dispatcher) } Use Dispatcher -
class UsersRepository( val apiService: ApiService, val dispatcher: CoroutineDispatcher ) {
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC" } .map { Result.success(it.name) } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } -
@Test fun `should get users`() = runBlockingTest { usersRepository.getUsers().test {
expectError() } } How do I use a custom dispatcher? -
@Test fun `should get users`() = runBlockingTest { usersRepository.getUsers().test {
expectError() } } fun TestCoroutineDispatcher.runBlockingTest(""...) -
val dispatcher = TestCoroutineDispatcher() val usersRepository = UsersRepository(""..., dispatcher) @Test
fun `should get users`() = dispatcher.runBlockingTest { usersRepository.getUsers().test { expectError() } } -
val dispatcher = TestCoroutineDispatcher() val usersRepository = UsersRepository(""..., dispatcher) @Test
fun `should get users`() = dispatcher.runBlockingTest { usersRepository.getUsers().test { expectError() } } -
val dispatcher = TestCoroutineDispatcher() val usersRepository = UsersRepository(""..., dispatcher) @Test
fun `should get users`() = dispatcher.runBlockingTest { usersRepository.getUsers().test { expectError() } } -
Flow Test Cases • Collection • Run on Dispatcher •
Errors • Retries Fail • Retry Succeeds -
class UsersRepository(val apiService: ApiService) { fun getUsers(): Flow<String> { return
apiService.getUsers() .filter { it.location "== "NYC" } .map { it.name } } } Test Error? -
@Test fun `should handle error`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) usersRepository.getUsers().test
{ expectError() } } Mock API method -
@Test fun `should handle error`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw Exception() } usersRepository.getUsers().test { expectError() } } Throw exception -
@Test fun `should handle error`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw Exception() } usersRepository.getUsers().test { expectError() } } Verify error is thrown -
@Test fun `should handle error`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw Exception() } usersRepository.getUsers().test { expectError() } } UserRepoTests.kt Run: should handle error UserRepoTest -
@Test fun `should handle error`() = runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw Exception() } usersRepository.getUsers().test { expectError() } } UserRepoTests.kt Run: should handle error UserRepoTest Try Catch -
class UsersRepository(val apiService: ApiService) { fun getUsers(): Flow<String> = apiService.getUsers()
.filter { it.location "== "NYC" } .map { it.name } } Better way to handle errors? -
inline class Result { fun <T> success(value: T) fun <T>
failure(exception: Throwable) } Union to represent success or failure -
fun getUsers(): Flow<Result<String">> = return apiService.getUsers() .filter { it.location "==
"NYC" } .map { Result.success(it.name) } .catch { emit(Result.failure(it)) } Flow emits Results -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .catch { emit(Result.failure(it)) } Success -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .catch { emit(Result.failure(it)) } Emit Result Failure -
@Test fun `should handle error`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw Exception() } usersRepository.getUsers().test { } } -
@Test fun `should handle error`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw Exception() } usersRepository.getUsers().test { expectItem().isFailure.shouldBeTrue() expectComplete() } } Verify Result is failure -
@Test fun `should handle error`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw Exception() } usersRepository.getUsers().test { expectItem().isFailure expectComplete() } } Verify no more emissions -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .catch { emit(Result.failure(it)) } Exception -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .catch { emit(Result.failure(it)) } Emit Result item -
Flow Test Cases • Collection • Run on Dispatcher •
Errors • Retries Fail • Retry Succeeds -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Exception -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Catch Exception -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Retry? -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Retry 2-times -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Delay for each retry -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Error -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Retry -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Delay 2 seconds -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Try running Flow again -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Retry fails, go to catch -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) How do we test retries? -
@Test fun `should retry twice`() = dispatcher.runBlockingTest { usersRepository.getUsers().test {
advanceTimeBy(2000) advanceTimeBy(2000) expectItem().isFailure.shouldBeTrue() expectComplete() } } -
@Test fun `should retry twice`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw IOException() } usersRepository.getUsers().test { advanceTimeBy(2000) advanceTimeBy(2000) expectItem().isFailure.shouldBeTrue() expectComplete() } } Throw Exception -
@Test fun `should retry twice`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw IOException() } usersRepository.getUsers().test { expectItem().isFailure.shouldBeTrue() expectComplete() } } Read from Flow -
@Test fun `should retry twice`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw IOException() } usersRepository.getUsers().test { expectItem().isFailure.shouldBeTrue() expectComplete() } } Verify Result is Failure -
@Test fun `should retry twice`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw IOException() } usersRepository.getUsers().test { expectItem().isFailure.shouldBeTrue() expectComplete() } } -
@Test fun `should retry twice`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw IOException() } usersRepository.getUsers().test { expectItem().isFailure.shouldBeTrue() expectComplete() } } UserRepoTests.kt Run: UserRepoTest should retry twice kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 1000 ms ! ! Timeout Exception -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Error -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Retry -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Delay 2 seconds -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Advance virtual time forward -
@Test fun `should retry twice`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw IOException() } usersRepository.getUsers().test { advanceTimeBy(2000) expectItem().isFailure.shouldBeTrue() expectComplete() } } Advance virtual time on dispatcher -
@Test fun `should retry twice`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw IOException() } usersRepository.getUsers().test { advanceTimeBy(2000) expectItem().isFailure.shouldBeTrue() expectComplete() } } Advance time by 2 seconds -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Retry -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Delay for before 2nd retry -
@Test fun `should retry twice`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw IOException() } usersRepository.getUsers().test { advanceTimeBy(2000) advanceTimeBy(2000) expectItem().isFailure.shouldBeTrue() expectComplete() } } Advance time forward for 2nd retry -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) 2nd Retry -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) All Retries failed -
@Test fun `should retry twice`() = dispatcher.runBlockingTest { whenever(apiService.getUsers()) doReturn
flow { throw IOException() } usersRepository.getUsers().test { advanceTimeBy(2000) advanceTimeBy(2000) expectItem().isFailure.shouldBeTrue() expectComplete() } } -
Flow Test Cases • Collection • Run on Dispatcher •
Errors • Retries Fail • Retry Succeeds -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) 2nd Retry Succeeds -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Apply Filter, Map -
var throwError = false whenever(apiService.getUsers()) doReturn flow { if (throwError)
{ throw IOException() } else { emit(User(1, "User 1", "NYC")) } } Flag to control sending error -
var throwError = false whenever(apiService.getUsers()) doReturn flow { if (throwError)
{ throw IOException() } else { emit(User(1, "User 1", "NYC")) } } Mock API Service to return Flow -
var throwError = false whenever(apiService.getUsers()) doReturn flow { if (throwError)
{ throw IOException() } else { emit(User(1, "User 1", "NYC")) } } Throw Error on exception -
var throwError = false whenever(apiService.getUsers()) doReturn flow { if (throwError)
{ throw IOException() } else { emit(User(1, "User 1", "NYC")) } } Emit User -
@Test fun `should retry succeed`() = dispatcher.runBlockingTest { usersRepository.getUsers().test {
advanceTimeBy(2000) throwError = false advanceTimeBy(2000) expectItem().isSuccess.shouldBeTrue() expectComplete() } } Retry -
@Test fun `should retry succeed`() = dispatcher.runBlockingTest { usersRepository.getUsers().test {
advanceTimeBy(2000) throwError = false advanceTimeBy(2000) expectItem().isSuccess.shouldBeTrue() expectComplete() } } Flow will return data -
@Test fun `should retry succeed`() = dispatcher.runBlockingTest { usersRepository.getUsers().test {
advanceTimeBy(2000) throwError = false advanceTimeBy(2000) expectItem().isSuccess.shouldBeTrue() expectComplete() } } 2nd Retry -
@Test fun `should retry succeed`() = dispatcher.runBlockingTest { usersRepository.getUsers().test {
advanceTimeBy(2000) throwError = false advanceTimeBy(2000) expectItem().isSuccess.shouldBeTrue() expectComplete() } } Verify Success -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) 2nd Retry -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) -
fun getUsers(): Flow<Result<String">> = apiService.getUsers() .filter { it.location "== "NYC"
} .map { Result.success(it.name) } .retry(2) { delay(2000) true } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) Operators -
@Test fun `should retry succeed`() = dispatcher.runBlockingTest { usersRepository.getUsers().test {
advanceTimeBy(2000) throwError = false advanceTimeBy(2000) expectItem().isSuccess.shouldBeTrue() expectComplete() } } -
Flow Test Cases • Collection • Run on Dispatcher •
Errors • Retries Fail • Retry Succeeds -
class UserViewModel(): ViewModel() { val states = MutableStateFlow(State()) fun getData()
{ usersRepository.getUsers() .onEach { states.value = State(data = it.get()) } .launchIn(viewModelScope) } } data class State(val data: String = "") Jetpack View Model -
class UserViewModel(val usersRepository: UsersRepository): ViewModel() { val states = MutableStateFlow(State())
fun getData() { usersRepository.getUsers() .onEach { states.value = State(data = it.get()) } .launchIn(viewModelScope) } } data class State(val data: String = "") Inject Repo -
class UserViewModel(val usersRepository: UsersRepository): ViewModel() { val states = MutableStateFlow("")
fun getData() { usersRepository.getUsers() .onEach { states.value = State(data = it.get()) } .launchIn(viewModelScope) } } State Flow -
class UserViewModel(val usersRepository: UsersRepository): ViewModel() { val states = MutableStateFlow("")
fun getData() { usersRepository.getUsers() .onEach { states.value = State(data = it.get()) } .launchIn(viewModelScope) } } Flow of user names -
class UserViewModel(val usersRepository: UsersRepository): ViewModel() { val states = MutableStateFlow("")
fun getData() { usersRepository.getUsers() .onEach { states.value = it } .launchIn(viewModelScope) } } Update State flow for each emission -
class UserViewModel(val usersRepository: UsersRepository): ViewModel() { val states = MutableStateFlow("")
fun getData() { usersRepository.getUsers() .onEach { states.value = it } .launchIn(viewModelScope) } } Launch coroutine in view module sopce -
class UserViewModel(val usersRepository: UsersRepository): ViewModel() { val states = MutableStateFlow("")
fun getData() { usersRepository.getUsers() .onEach { states.value = it } .launchIn(viewModelScope) } } -
@Test fun `should get data`() = runBlockingTest { whenever(repo.getUsers()) doReturn
flowOf(Result.success("User")) viewModel.getData() viewModel.states.test { expectItem().data shouldBe "User" } } -
@Test fun `should get data`() = runBlockingTest { whenever(repo.getUsers()) doReturn
flowOf(Result.success("User")) viewModel.getData() viewModel.states.test { expectItem().data shouldBe "User" } } Mock flow -
@Test fun `should get data`() = runBlockingTest { whenever(repo.getUsers()) doReturn
flowOf("User") viewModel.getData() viewModel.states.test { expectItem().data shouldBe "User" } } Emit Successful response -
@Test fun `should get data`() = runBlockingTest { whenever(repo.getUsers()) doReturn
flowOf("User") viewModel.getData() viewModel.states.test { expectItem().data shouldBe "User" } } Run test -
@Test fun `should get data`() = runBlockingTest { whenever(repo.getUsers()) doReturn
flowOf("User") viewModel.getData() viewModel.states.test { expectItem().data shouldBe "User" } } Verify emission -
@Test fun `should get data`() = runBlockingTest { whenever(repo.getUsers()) doReturn
flowOf(Result.success("User")) viewModel.getData() viewModel.states.test { expectItem().data shouldBe "User" } } ViewModelTest.kt Run: ViewModelTest should get data Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used -
val dispatcher = TestCoroutineDispatcher() @Before fun setUp() { Dispatchers.setMain(dispatcher) }
@After fun tearDown() { Dispatchers.resetMain() } Set Main Dispatcher -
val dispatcher = TestCoroutineDispatcher() @Before fun setUp() { Dispatchers.setMain(dispatcher) }
@After fun tearDown() { Dispatchers.resetMain() } Reset Main Dispatcher -
class CoroutineTestRule(testDispatcher) : TestWatcher() { override fun starting(description) { Dispatchers.setMain(testDispatcher)
} override fun finished(description) { Dispatchers.resetMain() testDispatcher.cleanupTestCoroutines() } } -
class CoroutineTestRule(testDispatcher) : TestWatcher() { override fun starting(description) { Dispatchers.setMain(testDispatcher)
} override fun finished(description) { Dispatchers.resetMain() testDispatcher.cleanupTestCoroutines() } } -
class CoroutineTestRule(testDispatcher) : TestWatcher() { override fun starting(description) { Dispatchers.setMain(testDispatcher)
} override fun finished(description) { Dispatchers.resetMain() testDispatcher.cleanupTestCoroutines() } } -
@get:Rule var testRule = CoroutineTestRule() @Test fun `should get data`()
= runBlockingTest { whenever(repo.getUsers()) doReturn flowOf("User") viewModel.getData() viewModel.states.test { expectItem().data shouldBe "User" } } -
@get:Rule var testRule = CoroutineTestRule() @Test fun `should get data`()
= runBlockingTest { whenever(repo.getUsers()) doReturn flowOf(Result.success("User")) viewModel.getData() viewModel.states.test { expectItem().data shouldBe "User" } } ViewModelTest.kt Run: ViewModelTest should get data -
@Test fun `should get data`() = runBlockingTest { whenever(repo.getUsers()) doReturn
flowOf( "User 1", "User 2" ) viewModel.getData() viewModel.states.test { expectItem().data shouldBe "User 1" expectItem().data shouldBe "User 2" expectComplete() } Return 2 results -
@Test fun `should get data`() = runBlockingTest { whenever(repo.getUsers()) doReturn
flowOf( "User 1", "User 2" ) viewModel.getData() viewModel.states.test { expectItem().data shouldBe "User 1" expectItem().data shouldBe "User 2" expectComplete() } Return 2 results -
@Test fun `should get data`() = runBlockingTest { viewModel.getData() viewModel.states.test
{ expectItem().data shouldBe "User 1" expectItem().data shouldBe "User 2" expectComplete() } Verification -
@Test fun `should get data`() = runBlockingTest { viewModel.getData() viewModel.states.test
{ expectItem().data shouldBe "User 1" expectItem().data shouldBe "User 2" expectComplete() } ViewModelTest.kt Run: ViewModelTest should get data java.lang.AssertionError: Expected <User 1>, actual <User 2> are not the same instance. -
@Test fun `should get data`() = runBlockingTest { viewModel.getData() viewModel.states.test
{ expectItem().data shouldBe "User 1" expectItem().data shouldBe "User 2" expectComplete() } ViewModelTest.kt Run: ViewModelTest should get data java.lang.AssertionError: Expected <User 1>, actual <User 2> are not the same instance. Assertion failed -
class UserViewModel(val usersRepository: UsersRepository): ViewModel() { val states = MutableStateFlow(State())
fun getData() { usersRepository.getUsers() .onEach { states.value = State(it) } .launchIn(viewModelScope) } } Conflated -
Channels • Broadcast Channel • Unlimited Channel • Buffered Channel
• Mutable Shared Flow -
class UserViewModel(val usersRepository: UsersRepository): ViewModel() { val sharedFlow = MutableSharedFlow<String>()
fun getData() { usersRepository.getUsers() .onEach { states.emit(it) } .launchIn(viewModelScope) } } -
Channels • Broadcast Channel • Unlimited Channel • Buffered Channel
• Mutable Shared Flow -
class JobBasicCancellationTest : TestBase() { @Test fun testCancelJobImpl() { }
} Defines utilities -
class JobBasicCancellationTest : TestBase() { @Test fun testCancelJobImpl() { }
} Test parent job is not cancelled -
@Test fun testCancelJobImpl() = runTest { val parent = launch
{ expect(1) val child = Job(coroutineContext[Job]) expect(2) child.cancel() child.join() expect(3) } parent.join() finish(4) } -
@Test fun testCancelJobImpl() = runTest { val parent = launch
{ expect(1) val child = Job(coroutineContext[Job]) expect(2) child.cancel() child.join() expect(3) } parent.join() finish(4) } Launch coroutine -
@Test fun testCancelJobImpl() = runTest { val parent = launch
{ expect(1) val child = Job(coroutineContext[Job]) expect(2) child.cancel() child.join() expect(3) } parent.join() finish(4) } Child coroutine Job -
@Test fun testCancelJobImpl() = runTest { val parent = launch
{ expect(1) val child = Job(coroutineContext[Job]) expect(2) child.cancel() child.join() expect(3) } parent.join() finish(4) } Cancel the job -
@Test fun testCancelJobImpl() = runTest { val parent = launch
{ expect(1) val child = Job(coroutineContext[Job]) expect(2) child.cancel() child.join() expect(3) } parent.join() finish(4) } Verify order of execution Verify completion -
@Test fun testCancelJobImpl() = runTest { val parent = launch
{ expect(1) val child = Job(coroutineContext[Job]) expect(2) child.cancel() child.join() expect(3) } parent.join() finish(4) } -
expect open class TestBase { fun error(message, cause) fun expect(index:
Int) fun finish(index: Int) fun runTest( block: suspend CoroutineScope.() "-> Unit ) } -
actual fun runTest( block: suspend CoroutineScope.() "-> Unit ) {
runBlocking( block = block, context = CoroutineExceptionHandler { ""... }) } -
expect open class TestBase { fun error(message, cause) fun expect(index:
Int) fun finish(index: Int) fun runTest( block: suspend CoroutineScope.() "-> Unit ) } How does this work? -
private var actionIndex = AtomicInteger() actual fun expect(index: Int) {
val wasIndex = actionIndex.incrementAndGet() check(index "== wasIndex) { “Expecting action index $index but it is actually $wasIndex" } } -
private var actionIndex = AtomicInteger() actual fun expect(index: Int) {
val wasIndex = actionIndex.incrementAndGet() check(index "== wasIndex) { “Expecting action index $index but it is actually $wasIndex" } } -
private var actionIndex = AtomicInteger() actual fun expect(index: Int) {
val wasIndex = actionIndex.incrementAndGet() check(index "== wasIndex) { “Expecting action index $index but it is actually $wasIndex" } } -
expect open class TestBase { fun error(message, cause) fun expect(index:
Int) fun finish(index: Int) fun runTest( block: suspend CoroutineScope.() "-> Unit ) } How does this work? -
private var finished = AtomicBoolean() actual fun finish(index: Int) {
expect(index) check(!finished.getAndSet(true)) { "Should call 'finish(""...)' at most once" } } -
private var finished = AtomicBoolean() actual fun finish(index: Int) {
expect(index) check(!finished.getAndSet(true)) { "Should call 'finish(""...)' at most once" } } -
private var finished = AtomicBoolean() actual fun finish(index: Int) {
expect(index) check(!finished.getAndSet(true)) { "Should call 'finish(""...)' at most once" } } -
@Test fun testCancelJobImpl() = runTest { val parent = launch
{ expect(1) val child = Job(coroutineContext[Job]) expect(2) child.cancel() child.join() expect(3) } parent.join() finish(4) } -
Resources • Unit Testing Delays, Errors & Retries with Kotlin
Flows https:"//codingwithmohit.com/coroutines/unit-testing-delays- errors-retries-with-kotlin-flows/ • Unit Testing Channels & Flows in Practice https:"//www.youtube.com/watch?v=h8bLIUi6HWU