Share
Embed
Transcript
183 slides
-
Unit Testing Kotlin Flows • Foundations • Useful Libraries •
State Flows • Shared Flows -
flowOfData: Flow<Data> .filter { ... } .map { ... }
.flatmap { ... } -
flowOfData: Flow<Data> .filter { ... } .map { ... }
.flatmap { ... } How do we test this flow? -
@Test fun `should get data`() = runBlockingTest { } Test
Scope + Test Dispatcher -
@Test fun `should get data`() = runBlockingTest { } Test
Scope + Test Dispatcher What is executed in this coroutine? -
@Test fun `should get data`() = runBlockingTest { } Test
Scope + Test Dispatcher -
@Test fun `should get data`() = runBlockingTest { } Test
Scope + Test Dispatcher -
flowOfData: Flow<Data> .filter { ... } .map { ... }
.flatmap { ... } -
@Test fun `should get data`() = runBlockingTest { val flowOfData
= mockFlow() val locations: List<Location> = flowOfLocations.toList() } Create Mock Flow -
@Test fun `should get data`() = runBlockingTest { val flowOfData
= mockFlow() val items: List<Data> = flowOfData.toList() } -
@Test fun `should get locations`() = runBlockingTest { val items:
List<Data> = flowOfData.toList() } -
@Test fun `should get locations`() = runBlockingTest { val items:
List<Data> = flowOfData.toList() } -
@Test fun `should get locations`() = runBlockingTest { val items:
List<Data> = flowOfData.toList() } -
@Test fun `should get locations`() = runBlockingTest { val items:
List<Data> = flowOfData.toList() } -
@Test fun `should get locations`() = runBlockingTest { val items:
List<Data> = flowOfData.toList() items shouldContainAll listOf(item1, item2, item3) } -
@Test fun `should get data`() = runBlockingTest { val flowOfData
= mockFlow() val items: List<Data> = flowOfData.toList() items shouldContainAll listOf(item1, item2, item3) } -
@Test fun `should get data`() = runBlockingTest { val locations:
List<Location> = flowOfLocations.toList() locations shouldContainAll listOf(location1, location2, location3) } How does this work? -
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() } dispatcher.advanceUntilIdle() deferred.getCompletionExceptionOrNull() ?. let { throw it } scope.cleanupTestCoroutines() if (activeJobs()).isNotEmpty()) { throw UncompletedCoroutinesError("Test finished with active jobs") } } Setup -
fun runBlockingTest(testBody) { val scope = TestCoroutineScope(safeContext) val
deferred = scope.async { scope.testBody() } dispatcher.advanceUntilIdle() deferred.getCompletionExceptionOrNull() ?. let { throw it } scope.cleanupTestCoroutines() if (activeJobs()).isNotEmpty()) { throw UncompletedCoroutinesError("Test finished with active jobs") } } Setup Run Test -
fun runBlockingTest(testBody) { val scope = TestCoroutineScope(safeContext) val
deferred = scope.async { scope.testBody() } dispatcher.advanceUntilIdle() deferred.getCompletionExceptionOrNull() ?. let { throw it } scope.cleanupTestCoroutines() if (activeJobs()).isNotEmpty()) { throw UncompletedCoroutinesError("Test finished with active jobs") } } Setup Run Test Cleanup -
@Test fun `should get data`() = runBlockingTest { val flowOfData
= mockFlow() val items: List<Data> = flowOfData.toList() items shouldContainAll listOf(items1, items2, items3) } -
Run Blocking Test Different Approaches 1. Use run blocking test
for all tests 2. Testing Delays -> Use run blocking test 3. Non Delay Uses Cases -> Use run blocking -
@Test fun `should get data`() = runBlockingTest { val flowOfLocations
= mockFlow() val items: List<Data> = flowOfData.toList() locations shouldContainAll listOf(location1, location2, location3) } Better way to collect from Flows? -
cashApp/turbine Code ! Issues Pull Requests Turbine Small testing library
for kotlinx.coroutines Flow. testImplementation ‘app.cash.turbine:turbine:x.x.x' -
Test Cases • Verify order of items • Completion •
Error • Timeouts -
What Turbine Provides? suspend fun <T> Flow<T>.test( ... ) coroutineScope
{ val events = Channel<Event<T >> (UNLIMITED) launch { try { collect { ... } } catch { events.send(Event.Error) } -
interface FlowTurbine { suspend fun expectItem(): T fun expectNoEvents() fun
expectError(): Throwable suspend fun expectComplete() } What Turbine Provides? -
interface FlowTurbine { suspend fun expectItem(): T fun expectNoEvents() fun
expectError(): Throwable suspend fun expectComplete() } What Turbine Provides? -
interface FlowTurbine { suspend fun expectItem(): T fun expectNoEvents() fun
expectError(): Throwable suspend fun expectComplete() } What Turbine Provides? -
interface FlowTurbine { suspend fun expectItem(): T fun expectNoEvents() fun
expectError(): Throwable suspend fun expectComplete() } What Turbine Provides? -
Test Cases • Verify order of items • Completion •
Error • Timeouts -
@Test fun `should get data`() = runBlockingTest { flowOfData.test {
expectItem() shouldBeEqualTo location1 expectItem() shouldBeEqualTo location2 expectItem() shouldBeEqualTo location3 expectComplete() } } -
@Test fun `should get data`() = runBlockingTest { flowOfData.test {
expectItem() shouldBeEqualTo location1 expectItem() shouldBeEqualTo location2 expectItem() shouldBeEqualTo location3 expectComplete() } } Get first emitted item -
@Test fun `should get data`() = runBlockingTest { flowOfData.test {
expectItem() shouldBeEqualTo item1 expectItem() shouldBeEqualTo location2 expectItem() shouldBeEqualTo location3 expectComplete() } } Assertion -
@Test fun `should get data`() = runBlockingTest { flowOfData.test {
expectItem() shouldBeEqualTo item1 expectItem() shouldBeEqualTo item2 expectItem() shouldBeEqualTo item3 expectComplete() } } Get 1st, 2nd, 3rd item -
@Test fun `should get data`() = runBlockingTest { flowOfData.test {
expectItem() shouldBeEqualTo item1 expectItem() shouldBeEqualTo item2 } } Missed collecting item -
@Test fun `should get data`() = runBlockingTest { flowOfData.test {
expectItem() shouldBeEqualTo item1 expectItem() shouldBeEqualTo item2 } } RepoTest.kt Run: app.cash.turbine.AssertionError: Expected complete but found Item(Data(…)) DataRepoTests should get data -
Test Cases • Verify order of items • Completion •
Error • Timeouts -
@Test fun `should get locations`() = runBlockingTest { flowOfData.test {
expectItem() shouldBeEqualTo item1 expectItem() shouldBeEqualTo item2 expectItem() shouldBeEqualTo item3 expectComplete() } } -
@Test fun `should get locations`() = runBlockingTest { flowOfData.test {
expectItem() shouldBeEqualTo item1 expectItem() shouldBeEqualTo item2 expectItem() shouldBeEqualTo item3 } } RepoTests.kt Run: DataRepoTests should get data app.cash.turbine.AssertionError: Unconsumed events found: - Complete -
@Test fun `should get locations`() = runBlockingTest { flowOfData.test {
expectItem() shouldBeEqualTo item1 expectItem() shouldBeEqualTo item2 expectItem() shouldBeEqualTo item3 expectComplete() } } -
sealed class Event<out T> { object Complete data
class Error( ... ) data class Item(val value: T) } How Turbine Works Channel (Unlimited) Event -
Exception data class Error( ... ): Event() How Turbine Works
Channel (Unlimited) -
object Complete: Event() How Turbine Works Channel (Unlimited) How do
I query items in channels? -
interface FlowTurbine<T> { val timeout: Duration fun expectNoEvents() suspend fun
expectItem(): T fun expectError(): Throwable suspend fun expectComplete() } API to query Channel 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( 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 locations`() = runBlockingTest { flowOfLocations.test {
expectItem() shouldBeEqualTo location1 expectItem() shouldBeEqualTo location2 expectItem() shouldBeEqualTo location3 expectComplete() } } -
State Flow sealed class UiState { data class Error(
val exception: Throwable ): UiState() } -
State Flow sealed class UiState { data class Success(
val data: Data ): UiState() data class Error( val exception: Throwable ): UiState() } -
State Flow sealed class UiState { data class Success(
val data: Data ): UiState() data class Error( val exception: Throwable ): UiState() } -
State Flow val stateFlow = MutableStateFlow(UiState.Success(Data())) @Test fun `should emit
default value`() = runBlockingTest { stateFlow.test { expectItem() shouldBe UIState.Success } } -
State Flow @Test fun `should emit default value`() = runBlockingTest
{ stateFlow.test { expectItem() shouldBe UIState.Success expectComplete() } } -
State Flow @Test fun `should emit default value`() = runBlockingTest
{ stateFlow.test { expectItem() shouldBe UIState.Success expectComplete() } } ! Timed out waiting for 1000 ms kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 1000 ms -
State Flow suspend fun <T> Flow<T>.test( ... ) { coroutineScope
{ val events = Channel<Event<T >> (UNLIMITED) launch { collect { item -> events.send(Event.Item(item)) } events.send(Event.Complete) } } -
State Flow Behavior • Flow never completes normally • Subscribers
can complete exceptionally -
val stateFlow = MutableStateFlow(UiState.Success(Data())) State Flow stateFlow .onCompletion { println("ON
COMPLETE") } .collect { println(it) } -
val stateFlow = MutableStateFlow(UiState.Success(Data())) State Flow stateFlow .onCompletion { println("ON
COMPLETE") } .collect { println(it) } Will not log -
@Test fun `should emit default value`() = runBlockingTest { stateFlow
.onCompletion { println("ON COMPLETE") } .test { expectItem() shouldBe UIState.Success } } State Flow -
@Test fun `should emit default value`() = runBlockingTest { stateFlow
.onCompletion { println("ON COMPLETE") } .test { expectItem() shouldBe UIState.Success } } State Flow Will log -
How Turbine Works suspend fun <T> Flow<T>.test( ... ) {
coroutineScope { val collectJob = launch { collect { item -> ... } ... } ... collectJob.cancel() } -
@Test fun `should emit default value`() = runBlockingTest { stateFlow
.onCompletion { println("ON COMPLETE") } .test { expectItem() shouldBe UIState.Success } } State Flow Will log -
State Flow Features • Conflate Flow Emissions • Get most
recent emitted item -
val stateFlow = MutableStateFlow<UIState>(UIState.Success) @Test fun `should emit default value`()
= runBlockingTest { stateFlow.emit(UIState.Error) stateFlow.test { expectItem() shouldBe UIState.Success expectItem() shouldBe UIState.Error } } State Flow -
val stateFlow = MutableStateFlow<UIState>(UIState.Success) @Test fun `should emit default value`()
= runBlockingTest { stateFlow.emit(UIState.Error) stateFlow.test { expectItem() shouldBe UIState.Success expectItem() shouldBe UIState.Error } } State Flow -
val stateFlow = MutableStateFlow<UIState>(UIState.Success) @Test fun `should emit default value`()
= runBlockingTest { stateFlow.emit(UIState.Error) stateFlow.test { expectItem() shouldBe UIState.Success expectItem() shouldBe UIState.Error } } State Flow Fail -
val stateFlow = MutableStateFlow<UIState>(UIState.Success) @Test fun `should emit default value`()
= runBlockingTest { stateFlow.emit(UIState.Error) stateFlow.test { expectItem() shouldBe UIState.Success expectItem() shouldBe UIState.Error } } State Flow Most Recent Emission -
val stateFlow = MutableStateFlow<UIState>(UIState.Success) @Test fun `should emit default value`()
= runBlockingTest { stateFlow.emit(UIState.Error) stateFlow.test { expectItem() shouldBe UIState.Error } } State Flow Success -
State Flow Features • Conflate Flow Emissions • Get most
recent emitted item -
Mocking Flows class FakeRepository: Repository { private val channel =
Channel<Result>() } -
Mocking Flows class FakeRepository: Repository { private val channel =
Channel<Result>() override fun getData(): Flow<Result> { return channel.consumeAsFlow() } } -
Mocking Flows class FakeRepository: Repository { private val channel =
Channel<Result>() suspend fun emitResult(result: Result) { channel.send(result) } } -
Mocking Flows class FakeRepository: Repository { private val channel =
Channel<Result>() suspend fun emitFailure(result: Result.Failure) { channel.send(result) } } -
Mocking Flows class FakeRepository: Repository { private val channel =
Channel<Result>() fun closeChannel() = apply { channel.close() } } -
Mocking Flows class FakeRepository: Repository { val _stateFlow = MutableStateFlow<Result>(Result.Success)
val stateFlow = _stateFlow.asStateFlow() } -
Mocking Flows class FakeRepository: Repository { val _stateFlow = MutableStateFlow<Result>(Result.Success)
fun emitResult(result: Result) { _stateFlow.value = result } } -
State Flow Considerations • Hard to test back to back
emissions • Conflates emissions -
Better Approach • Use Shared Flow • Test the effects
of each emission -
State Flow State Flow Flow 1 Flow 2 Flow 3
Combined Flow -
Flow Combine 1 2 A 1A 2A Flow 1 Flow
2 Combined -
Flow Combine 1 2 A 1A 2A Flow 1 Flow
2 Combined B 2B -
val stateFlow = MutableStateFlow<UIState>(UIState.Success) flow1.combine(flow2) { a, b ->
combineItems(a, b) } State Flow -
val stateFlow = MutableStateFlow<UIState>(UIState.Success) flow1.combine(flow2) { a, b ->
combineItems(a, b) }.collect { stateFlow.emit(it) } State Flow -
@Test fun `should combine flows`() = runBlockingTest { val
mockFlow1 = mockFlow() val mockFlow2 = mockFlow() } State Flow -
@Test fun `should combine flows`() = runBlockingTest { val
mockFlow1 = mockFlow() val mockFlow2 = mockFlow() val stateHolder = StateHolder(mockFlow1, mockFlow2) } State Flow -
@Test fun `should combine flows`() = runBlockingTest {
val stateHolder = StateHolder(mockFlow1, mockFlow2) stateFlow.test { ... } } State Flow -
State Flow Challenges • Why didn’t the flow emit an
item? Conflated? • Too many flow combines makes it harder to follow the data flow -
Shared Flow val flow = MutableSharedFlow<String>() @Test fun `collect from
shared flow`() = runBlockingTest { flow.emit("Event 1") } -
Shared Flow val flow = MutableSharedFlow<String>() @Test fun `collect from
shared flow`() = runBlockingTest { flow.emit("Event 1") flow.test { expectItem() shouldBeEqualTo "Event 1" } } Failed -
Shared Flow val flow = MutableSharedFlow<String>() @Test fun `collect from
shared flow`() = runBlockingTest { flow.emit("Event 1") flow.test { expectItem() shouldBeEqualTo "Event 1" } } Subscriber count 0 -
Shared Flow val flow = MutableSharedFlow<String>() @Test fun `collect from
shared flow`() = runBlockingTest { flow.emit("Event 1") flow.test { expectItem() shouldBeEqualTo "Event 1" } } Flow doesn’t replay -
Shared Flow @Test fun `collect from shared flow`() = runBlockingTest
{ val job = launch(start = CoroutineStart.LAZY) { flow.emit("Event 1") } } -
Shared Flow @Test fun `collect from shared flow`() = runBlockingTest
{ val job = launch(start = CoroutineStart.LAZY) { flow.emit("Event 1") } } -
Shared Flow @Test fun `collect from shared flow`() = runBlockingTest
{ val job = launch(start = CoroutineStart.LAZY) { flow.emit("Event 1") } flow.test { job.start() expectItem() shouldBeEqualTo "Event 1" } } Subscriber count 1 -
Shared Flow @Test fun `collect from shared flow`() = runBlockingTest
{ val job = launch(start = CoroutineStart.LAZY) { flow.emit("Event 1") } flow.test { job.start() expectItem() shouldBeEqualTo "Event 1" } } Success -
@Test fun `collect from shared flow`() = runBlockingTest { flow.emit("Event
1") flow.test { expectItem() shouldBeEqualTo "Event 1" } } Shared Flow val flow = MutableSharedFlow<String>(replay = 1) Replay -
Mocking Flows class FakeRepository: Repository { val flow = MutableSharedFlow<Result>(
replay = 1, BufferOverFlow.DROP_OLDEST ) } -
Mocking Flows class FakeRepository: Repository { val flow = MutableSharedFlow<Result>(
replay = 1, BufferOverFlow.DROP_OLDEST ) suspend fun emitResult(result: Result) { flow.emit(result) } } -
While Subscribed @Test fun `collect with while subscribed strategy`() =
runBlockingTest { val sharingScope = TestCoroutineScope() val sharedFlow = flow .onStart { println("ON START") } .shareIn( sharingScope, SharingStarted.WhileSubscribed(), 1 ) } -
While Subscribed @Test fun `collect with while subscribed strategy`() =
runBlockingTest { val sharingScope = TestCoroutineScope() val sharedFlow = flow .shareIn( sharingScope, SharingStarted.WhileSubscribed(), 1 ) } -
While Subscribed @Test fun `collect with while subscribed strategy`() =
runBlockingTest { val sharingScope = TestCoroutineScope() val sharedFlow = flow .onStart { println("ON START") } .shareIn( sharingScope, SharingStarted.WhileSubscribed(), 1 ) } Will not log -
While Subscribed • Start upstream flow upon subscriber • Remain
active while external scope is active -
While Subscribed @Test fun `collect with while subscribed strategy`() =
runBlockingTest { val sharedFlow = flow .onStart { println("ON START") } .shareIn( ... ) sharedFlow.test { ... } } -
While Subscribed @Test fun `collect with while subscribed strategy`() =
runBlockingTest { val sharedFlow = flow .onStart { println("ON START") } .shareIn( ... ) sharedFlow.test { ... } } -
While Subscribed • Start upstream flow upon subscriber • Remain
active while there are subscribers -
Eagerly @Test fun `collect with eagerly strategy`() = runBlockingTest {
val sharedFlow = flow .onStart { println("ON START") } .shareIn( sharingScope, SharingStarted.Eagerly, 1 ) } -
Eagerly @Test fun `collect with eagerly strategy`() = runBlockingTest {
val sharedFlow = flow .onStart { println("ON START") } .shareIn( sharingScope, SharingStarted.Eagerly, 1 ) } Will start -
Lazily @Test fun `collect with lazily strategy`() = runBlockingTest {
val sharedFlow = flow .onStart { println("ON START") } .shareIn( sharingScope, SharingStarted.Lazily, 1 ) } Will start -
Lazily @Test fun `collect with lazily strategy`() = runBlockingTest {
val sharedFlow = flow .onComplete { println("ON Complete”) } .shareIn( sharingScope, SharingStarted.Lazily, 1 ) }