Slide 1

Slide 1 text

Mohit Sarveiya Unit Testing Kotlin Channels & Flows www.twitter.com/heyitsmohit www.codingwithmohit.com

Slide 2

Slide 2 text

Unit Test Kotlin Channels & Flows ● Use case with ViewModel & Repo ● Testing Repo & ViewModel ● Flow Assertions ● Test Pattern used in Coroutine Library

Slide 3

Slide 3 text

Repository Flow View Model

Slide 4

Slide 4 text

/users/{id} User Details

Slide 5

Slide 5 text

API Service interface ApiService { @GET("/users/{id}") suspend fun userDetails(@Path("id") id: Int): UserDetails }

Slide 6

Slide 6 text

Repository class UserRepository(val apiService: ApiService) { fun userDetails(id: Int): Flow> { } } How do we create this Flow?

Slide 7

Slide 7 text

fun userDetails(id: Int): Flow> { } fun flow( block: suspend FlowCollector.() "-> Unit ): Flow Creating Flow Coroutine Library

Slide 8

Slide 8 text

fun userDetails(id: Int): Flow> { } interface FlowCollector { suspend fun emit(value: T) } Coroutine Library Creating Flow

Slide 9

Slide 9 text

Creating Flow fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) } }

Slide 10

Slide 10 text

Creating Flow fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) } } separate thread?

Slide 11

Slide 11 text

Creating Flow fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) } } Coroutine Library fun Flow.flowOn(context: CoroutineContext): Flow

Slide 12

Slide 12 text

Creating Flow fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) } } Coroutine Library Dispatcher • Default, IO, Main, etc""...

Slide 13

Slide 13 text

Creating Flow class UserRepository( val apiService: ApiService, val dispatcher: CoroutineDispatcher ) { fun userDetails(id: Int): Flow> { return flow { val users = apiService.userDetails(id) emit(Result.success(users)) }.flowOn(dispatcher) }

Slide 14

Slide 14 text

Creating Flow class UserRepository( val apiService: ApiService, val dispatcher: CoroutineDispatcher ) { fun userDetails(id: Int): Flow> { return flow { val users = apiService.userDetails(id) emit(Result.success(users)) }.flowOn(dispatcher) }

Slide 15

Slide 15 text

Repository Flow View Model View Model

Slide 16

Slide 16 text

View Model class UserDetailViewModel : ViewModel { }

Slide 17

Slide 17 text

View Model class UserDetailViewModel : ViewModel { val scope = CoroutineScope(Dispatchers.Main) } Coroutine Library fun CoroutineScope(context: CoroutineContext)

Slide 18

Slide 18 text

View Model class UserDetailViewModel : ViewModel { val scope = CoroutineScope(Dispatchers.Main) scope.launch { } }

Slide 19

Slide 19 text

View Model class UserDetailViewModel( val repository: UserRepository ) : ViewModel { val scope = CoroutineScope(Dispatchers.Main) scope.launch { } }

Slide 20

Slide 20 text

View Model class UserDetailViewModel( val repository: UserRepository ) : ViewModel { val scope = CoroutineScope(Dispatchers.Main) scope.launch { val flow = repository.getUserDetails(id = 1) } }

Slide 21

Slide 21 text

View Model class UserDetailViewModel( val repository: UserRepository ) : ViewModel { val scope = CoroutineScope(Dispatchers.Main) scope.launch { val flow = repository.getUserDetails(id = 1) } } Coroutine Library fun Flow.collect( action: suspend (value: T) "-> Unit )

Slide 22

Slide 22 text

View Model class UserDetailViewModel( val repository: UserRepository ) : ViewModel { val scope = CoroutineScope(Dispatchers.Main) scope.launch { val flow = repository.getUserDetails(id = 1) flow.collect { result: Result "-> } }

Slide 23

Slide 23 text

View Model class UserDetailViewModel( val repository: UserRepository val reducer: Reducer ) : ViewModel { val scope = CoroutineScope(Dispatchers.Main) scope.launch { val flow = repository.getUserDetails(id = 1) flow.collect { result: Result "-> reducer.dispatchState(result) } }

Slide 24

Slide 24 text

View Model class UserDetailViewModel( val repository: UserRepository, val reducer: Reducer ) : ViewModel { val scope = CoroutineScope(Dispatchers.Main) scope.launch { val flow = repository.getUserDetails(id = 1) flow.collect { result: Result "-> reducer.dispatchState(result) } }

Slide 25

Slide 25 text

val ViewModel.viewModelScope: CoroutineScope get() { val scope: CoroutineScope? = this.getTag(JOB_KEY) return scope } View Model class UserDetailViewModel( val repository: UserRepository, val stateManager: StateManager ) : ViewModel { val scope = CoroutineScope(Dispatchers.Main) Architecture Components

Slide 26

Slide 26 text

Repository Flow View Model

Slide 27

Slide 27 text

Kotlin Coroutines Test Library • Test Coroutine Scope • Test Coroutine Dispatcher • runBlockingTest testImplementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-test:x.x.x'

Slide 28

Slide 28 text

Unit Test Repository Cases • Flow emits Success • Flow emits Error • Retries with delay (Advanced)

Slide 29

Slide 29 text

Repository class UserRepository( val apiService: ApiService, val dispatcher: CoroutineDispatcher ) { fun userDetails(id: Int): Flow> { return flow { val users = apiService.userDetails(id) emit(Result.success(users)) }.flowOn(dispatcher) }

Slide 30

Slide 30 text

@Test fun `should get users details on success`() = runBlocking { } Coroutine Library RunBlocking • Creates a coroutine • Blocks until coroutine completes

Slide 31

Slide 31 text

@Test fun `should get users details on success`() = runBlocking { val userDetails = UserDetails(1, "User 1", "avatar_url") val apiService = mock() } suspend fun userDetails(id: Int): UserDetails API Service

Slide 32

Slide 32 text

@Test fun `should get users details on success`() = runBlocking { val userDetails = UserDetails(1, "User 1", "avatar_url") val apiService = mock() { on { userDetails(1) } doReturn userDetails } Error: Suspend functions can only be called from suspend functions

Slide 33

Slide 33 text

@Test fun `should get users details on success`() = runBlocking { val userDetails = UserDetails(1, "User 1", "avatar_url") val apiService = mock() { on { userDetails(1) } doReturn userDetails } } Mockito Kotlin fun on(methodCall: T.() "-> R)

Slide 34

Slide 34 text

Mockito Kotlin fun onBlocking(m: suspend T.() "-> R) { return runBlocking { Mockito.`when`(mock.m()) } } @Test fun `should get users details on success`() = runBlocking { val userDetails = UserDetails(1, "User 1", "avatar_url") val apiService = mock() { on { userDetails(1) } doReturn userDetails } }

Slide 35

Slide 35 text

@Test fun `should get users details on success`() = runBlocking { val userDetails = UserDetails(1, "User 1", "avatar_url") val apiService = mock() { onBlocking { userDetails(1) } doReturn userDetails } }

Slide 36

Slide 36 text

@Test fun `should get users details on success`() = runBlocking { val userDetails = mockUserDetails() }

Slide 37

Slide 37 text

@Test fun `should get users details on success`() = runBlocking { val userDetails = mockUserDetails() val dispatcher = TestCoroutineDispatcher() val repository = UserRepository(userService, dispatcher) val flow = repository.getUserDetails(id = 1) }

Slide 38

Slide 38 text

@Test fun `should get users details on success`() = runBlocking { val userDetails = mockUserDetails() val dispatcher = TestCoroutineDispatcher() val repository = UserRepository(userService, dispatcher) val flow = repository.getUserDetails(id = 1) val result = flow.single() result.isSuccess.assertTrue() }

Slide 39

Slide 39 text

Unit Test Repository Cases • Flow emits Success • Flow emits Error • Retries with delay (Advanced)

Slide 40

Slide 40 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.flowOn(dispatcher) } Exception

Slide 41

Slide 41 text

View Model scope.launch { val flow: = userRepository.getUserDetails(id = 1) flow.collect { } } fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.flowOn(dispatcher) } Exception

Slide 42

Slide 42 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.flowOn(dispatcher) } Coroutine Library fun Flow.catch( action: suspend FlowCollector.(t: Throwable) "-> Unit ): Flow

Slide 43

Slide 43 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Exception

Slide 44

Slide 44 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Exception

Slide 45

Slide 45 text

@Test fun `should get error for user details`() = runBlocking { val apiService = mock { onBlocking { userDetails(1) } doAnswer { throw IOException() } } } Mock

Slide 46

Slide 46 text

@Test fun `should get error for user details`() = runBlocking { val apiService = mockApiService() val repository = UserRepository(apiService, dispatcher) val flow = repository.getUserDetails(id = 1) }

Slide 47

Slide 47 text

@Test fun `should get error for user details`() = runBlocking { val apiService = mockApiService() val repository = UserRepository(apiService, dispatcher) val flow = repository.getUserDetails(id = 1) val result = flow.single() result.isFailure.assertTrue() }

Slide 48

Slide 48 text

Unit Test Repository Cases • Flow emits Success • Flow emits Error • Retries with delay (Advanced)

Slide 49

Slide 49 text

/users/{id} Failed

Slide 50

Slide 50 text

/users/{id} - 2 Retries

Slide 51

Slide 51 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Exception

Slide 52

Slide 52 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Coroutine Library fun retry( retries: Long, block: suspend (Throwable) "-> Boolean ): Flow

Slide 53

Slide 53 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.retry(retries = 2) { t: Throwable "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) }

Slide 54

Slide 54 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.catch { emit(Result.failure(it)) } .retry(retries = 2) { t: Throwable "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Exception

Slide 55

Slide 55 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.catch { emit(Result.failure(it)) } .retry(retries = 2) { t: Throwable "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Retry

Slide 56

Slide 56 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.catch { emit(Result.failure(it)) } .retry(retries = 2) { t: Throwable "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Delay 1s

Slide 57

Slide 57 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.catch { emit(Result.failure(it)) } .retry(retries = 2) { t: Throwable "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Retry

Slide 58

Slide 58 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.retry(retries = 2) { t "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) }

Slide 59

Slide 59 text

Unit Test Retry Cases • All Retries fail with Error • Retry succeeds

Slide 60

Slide 60 text

runBlockingTest 1. Launch a coroutine with a test scope and test dispatcher. 2. Advance virtual time forward.

Slide 61

Slide 61 text

@Test fun `should retry with error`() { } Coroutine Library fun runBlockingTest( block: suspend TestCoroutineScope.() "-> Unit ) fun TestCoroutineDispatcher.runBlockingTest( block: suspend TestCoroutineScope.() "-> Unit )

Slide 62

Slide 62 text

val dispatcher = TestCoroutineDispatcher() @Test fun `should retry with error`() = dispatcher.runBlockingTest { } Create coroutines with test dispatcher

Slide 63

Slide 63 text

@Test fun `should retry with error`() = dispatcher.runBlockingTest { val apiService = mock { onBlocking { userDetails(1) } doAnswer { throw IOException() } } }

Slide 64

Slide 64 text

@Test fun `should retry with error`() = dispatcher.runBlockingTest { val apiService = mockApiService() val flow = repository.getUserDetails(id = 1) flow.collect { result: Result "-> result.isFailure.assertTrue() } }

Slide 65

Slide 65 text

@Test fun `should retry with error`() = dispatcher.runBlockingTest { val apiService = mockApiService() val flow = repository.getUserDetails(id = 1) flow.collect { result: Result "-> result.isFailure.assertTrue() } } runBlockingTest

Slide 66

Slide 66 text

@Test fun `should retry with error`() = dispatcher.runBlockingTest { val apiService = mockApiService() val flow = repository.getUserDetails(id = 1) flow.collect { result: Result "-> result.isFailure.assertTrue() } } runBlockingTest

Slide 67

Slide 67 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.retry(retries = 2) { t "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } runBlockingTest

Slide 68

Slide 68 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.retry(retries = 2) { t "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } runBlockingTest

Slide 69

Slide 69 text

fun userDetails(id: Int): Flow> { return flow { val users = userService.userDetails(id) emit(Result.success(users)) }.retry(retries = 2) { t "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } runBlockingTest Coroutines Test Library fun runBlockingTest { dispatcher.advanceUntilIdle() }

Slide 70

Slide 70 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) runBlockingTest

Slide 71

Slide 71 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.retry(retries = 2) { t: Throwable "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Catch Error. All retries failed.

Slide 72

Slide 72 text

@Test fun `should retry with error`() = dispatcher.runBlockingTest { val apiService = mockApiService() val flow = repository.getUserDetails(id = 1) flow.collect { result: Result "-> result.isFailure.assertTrue() } }

Slide 73

Slide 73 text

Unit Test Retry Cases • All Retries fail with Error • Retry succeeds

Slide 74

Slide 74 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.retry(retries = 2) { t "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Retry

Slide 75

Slide 75 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.retry(retries = 2) { t "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Success

Slide 76

Slide 76 text

runBlockingTest Features • Pause Dispatcher • Advance virtual time forward by certain milliseconds.

Slide 77

Slide 77 text

@Test fun `should retry with success`() = dispatcher.runBlockingTest { var throwError = true } Control API Response

Slide 78

Slide 78 text

@Test fun `should retry with success`() = dispatcher.runBlockingTest { var throwError = true val userDetails = UserDetails(1, "User 1", "avatar_url") } Successful Response

Slide 79

Slide 79 text

@Test fun `should retry with success`() = dispatcher.runBlockingTest { var throwError = true val userDetails = UserDetails(1, "User 1", "avatar_url") val apiService = mock { } }

Slide 80

Slide 80 text

@Test fun `should retry with success`() = dispatcher.runBlockingTest { var throwError = true val userDetails = UserDetails(1, "User 1", "avatar_url") val apiService = mock { onBlocking { userDetails(1) } doAnswer { if (throwError) throw IOException() else userDetails } } } Control API Response

Slide 81

Slide 81 text

@Test fun `should retry with success`() = dispatcher.runBlockingTest { val apiService = mockApiService() pauseDispatcher { } } Coroutine Test Library pausedDispatcher • Do not start coroutines eagerly

Slide 82

Slide 82 text

@Test fun `should retry with success`() = dispatcher.runBlockingTest { val apiService = mockApiService() pauseDispatcher { val flow = repository.getUserDetails(id = 1) launch { flow.collect { it.isSuccess.assertTrue() } } } Consumer

Slide 83

Slide 83 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.retry(retries = 2) { t: Throwable "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Run Flow

Slide 84

Slide 84 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.retry(retries = 2) { t: Throwable "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Suspend

Slide 85

Slide 85 text

@Test fun `should retry with success`() = dispatcher.runBlockingTest { val apiService = mockApiService() pauseDispatcher { val flow = repository.getUserDetails(id = 1) launch { flow.collect { it.isSuccess.assertTrue() } } advanceTimeBy(DELAY_ONE_SECOND) } } Advance virtual time

Slide 86

Slide 86 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.retry(retries = 2) { t: Throwable "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Retry

Slide 87

Slide 87 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.retry(retries = 2) { t: Throwable "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Suspend

Slide 88

Slide 88 text

@Test fun `should retry with success`() = dispatcher.runBlockingTest { val apiService = mockApiService() pauseDispatcher { val flow = repository.getUserDetails(id = 1) launch { flow.collect { it.isSuccess.assertTrue() } } advanceTimeBy(DELAY_ONE_SECOND) throwError = false } } Return success

Slide 89

Slide 89 text

@Test fun `should retry with success`() = dispatcher.runBlockingTest { val apiService = mockApiService() pauseDispatcher { val flow = repository.getUserDetails(id = 1) launch { flow.collect { it.isSuccess.assertTrue() } } advanceTimeBy(DELAY_ONE_SECOND) throwError = false advanceTimeBy(DELAY_ONE_SECOND) } } Advance virtual time

Slide 90

Slide 90 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.retry(retries = 2) { t: Throwable "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Retry

Slide 91

Slide 91 text

fun userDetails(id: Int): Flow> { return flow { val userDetails = apiService.userDetails(id) emit(Result.success(userDetails)) }.retry(retries = 2) { t: Throwable "-> (t is Exception).also { if (it) delay(DELAY_ONE_SECOND) } } .catch { emit(Result.failure(it)) } .flowOn(dispatcher) } Emit Success

Slide 92

Slide 92 text

@Test fun `should retry with success`() = dispatcher.runBlockingTest { val apiService = mockApiService() pauseDispatcher { val flow = repository.getUserDetails(id = 1) launch { flow.collect { it.isSuccess.assertTrue() } } advanceTimeBy(DELAY_ONE_SECOND) throwError = false advanceTimeBy(DELAY_ONE_SECOND) } } Collect

Slide 93

Slide 93 text

@Test fun `should retry with success`() = dispatcher.runBlockingTest { val apiService = mockApiService() pauseDispatcher { val flow = repository.getUserDetails(id = 1) launch { flow.collect { it.isSuccess.assertTrue() } } advanceTimeBy(DELAY_ONE_SECOND) throwError = false advanceTimeBy(DELAY_ONE_SECOND) } }

Slide 94

Slide 94 text

Unit Test Repository Cases • Flow emits Success • Flow emits Error • Retries with delay

Slide 95

Slide 95 text

Unit Test View Model Repository Flow View Model

Slide 96

Slide 96 text

View Model class UserDetailViewModel( val repository: UserRepository, val stateManager: StateManager ) : ViewModel { viewModelScope.launch { val flow = repository.getUserDetails(id = 1) flow.collect { result: Result "-> stateManager.dispatchState(result) } } }

Slide 97

Slide 97 text

View Model class UserDetailViewModel( val repository: UserRepository, val stateManager: StateManager ) : ViewModel { viewModelScope.launch { val flow = repository.getUserDetails(id = 1) flow.collect { result: Result "-> stateManager.dispatchState(result) } } } Main Dispatcher

Slide 98

Slide 98 text

Setting Main Dispatcher • Dispatchers.setMain() • Dispatchers.resetMain()

Slide 99

Slide 99 text

Test Rule class CoroutineTestRule( val dispatcher= TestCoroutineDispatcher() ) : TestWatcher() { override fun starting(description: Description?) { super.starting(description) Dispatchers.setMain(dispatcher) } }

Slide 100

Slide 100 text

Test Rule class CoroutineTestRule( val dispatcher= TestCoroutineDispatcher() ) : TestWatcher() { override fun finished(description: Description?) { super.finished(description) Dispatchers.resetMain() dispatcher.cleanupTestCoroutines() } }

Slide 101

Slide 101 text

View Model Test @get:Rule val rule = CoroutineTestRule()

Slide 102

Slide 102 text

View Model Test @get:Rule val rule = CoroutineTestRule() val repository = mock() val stateManager = mock() val viewModel = UserDetailsViewModel(repository, stateManager)

Slide 103

Slide 103 text

@Test fun `should dispatch details`() = rule.dispatcher.runBlockingTest { } Create coroutine with TestDispatcher

Slide 104

Slide 104 text

class UserDetailViewModel( val repository: UserRepository, val stateManager: StateManager ) : ViewModel { viewModelScope.launch { val flow = repository.getUserDetails(id = 1) flow.collect { result: Result "-> stateManager.dispatchState(result) } } } Mock Repo

Slide 105

Slide 105 text

class UserDetailViewModel( val repository: UserRepository, val stateManager: StateManager ) : ViewModel { viewModelScope.launch { val flow = repository.getUserDetails(id = 1) flow.collect { result: Result "-> stateManager.dispatchState(result) } } } Trigger Flow Collection

Slide 106

Slide 106 text

View Model Test Flow Send Channel Convert to Flow Receive

Slide 107

Slide 107 text

@Test fun `should dispatch details`() = rule.dispatcher.runBlockingTest { val userDetails = UserDetails(1, "User 1", "avatar") val result = Result.success(userDetails) }

Slide 108

Slide 108 text

@Test fun `should dispatch details`() = rule.dispatcher.runBlockingTest { val userDetails = UserDetails(1, "User 1", "avatar") val result = Result.success(userDetails) val channel = Channel>() } Channel

Slide 109

Slide 109 text

@Test fun `should dispatch details`() = rule.dispatcher.runBlockingTest { val userDetails = UserDetails(1, "User 1", "avatar") val result = Result.success(userDetails) val channel = Channel>() val flow = channel.consumeAsFlow() } Convert to Flow Flow Channel Convert to Flow

Slide 110

Slide 110 text

@Test fun `should dispatch details`() = rule.dispatcher.runBlockingTest { val userDetails = UserDetails(1, "User 1", "avatar") val result = Result.success(userDetails) val channel = Channel>() val flow = channel.consumeAsFlow() whenever(repository.getUserDetails(id = 1)) doReturn flow } Return Flow from Channel

Slide 111

Slide 111 text

@Test fun `should dispatch details`() = rule.dispatcher.runBlockingTest { val result = mockUserDetailsResult() val channel = Channel>() val flow = channel.consumeAsFlow() whenever(repository.getUserDetails(id = 1)) doReturn flow launch { channel.send(result) } } Producer to send values

Slide 112

Slide 112 text

@Test fun `should dispatch details`() = rule.dispatcher.runBlockingTest { val result = mockUserDetailsResult() val channel = Channel>() val flow = channel.consumeAsFlow() whenever(repository.getUserDetails(id = 1)) doReturn flow launch { channel.send(result) } userDetailsViewModel.getUserDetails() } Run test method

Slide 113

Slide 113 text

class UserDetailViewModel( val repository: UserRepository, val stateManager: StateManager ) : ViewModel { viewModelScope.launch { val flow = repository.getUserDetails(id = 1) flow.collect { result: Result "-> stateManager.dispatchState(result) } } } Collect result from Flow

Slide 114

Slide 114 text

@Test fun `should dispatch details`() = rule.dispatcher.runBlockingTest { val result = mockUserDetailsResult() val channel = Channel>() val flow = channel.consumeAsFlow() whenever(repository.getUserDetails(id = 1)) doReturn flow launch { channel.send(result) } userDetailsViewModel.getUserDetails() verify(stateManager).dispatch(result) } Verify result

Slide 115

Slide 115 text

Repository Flow View Model

Slide 116

Slide 116 text

Flow Assertions @Test fun `should get users details on success`() = runBlocking { ""... flow.collect { } flow.single() } RxJava Observable.test()

Slide 117

Slide 117 text

No content

Slide 118

Slide 118 text

Flow Assertions API fun expectItem(): T fun expectNoMoreEvents() fun expectComplete() fun expectError(): Throwable Test Flow Channel

Slide 119

Slide 119 text

sealed class Event { object Complete : Event() data class Error(val t: Throwable) : Event() data class Item(val item: T) : Event() } Flow Assertions Test Flow Channel

Slide 120

Slide 120 text

Flow Assertions sealed class Event { object Complete : Event() data class Error(val t: Throwable) : Event() data class Item(val item: T) : Event() } Item Test Flow Channel

Slide 121

Slide 121 text

Flow Assertions sealed class Event { object Complete : Event() data class Error(val t: Throwable) : Event() data class Item(val item: T) : Event() } Test Flow Channel Flow emission complete

Slide 122

Slide 122 text

sealed class Event { object Complete : Event() data class Error(val t: Throwable) : Event() data class Item(val item: T) : Event() } Flow Assertions Test Flow Channel Error

Slide 123

Slide 123 text

Flow Assertions suspend fun Flow.test( validate: suspend FlowAssert.() "-> Unit ) { }

Slide 124

Slide 124 text

Flow Assertions suspend fun Flow.test( validate: suspend FlowAssert.() "-> Unit ) { coroutineScope { val events = Channel>(UNLIMITED) } } Unlimited Buffered Channel

Slide 125

Slide 125 text

Flow Assertions suspend fun Flow.test( validate: suspend FlowAssert.() "-> Unit ) { coroutineScope { val events = Channel>(UNLIMITED) launch { collect { item "-> events.send(Event.Item(item)) } Event.Complete } } } Send to Channel

Slide 126

Slide 126 text

Flow Assertions suspend fun Flow.test( validate: suspend FlowAssert.() "-> Unit ) { coroutineScope { val events = Channel>(UNLIMITED) launch { try { sendToChannel() } catch (t: Throwable) { send(Event.Error(t)) } } } } Send Error

Slide 127

Slide 127 text

Flow Assertions suspend fun Flow.test( validate: suspend FlowAssert.() "-> Unit ) { coroutineScope { val events = Channel>(UNLIMITED) launch { collect { item "-> events.send(Event.Item(item)) } Event.Complete } } }

Slide 128

Slide 128 text

Flow Assertions class FlowAssert(val events: Channel>) { suspend fun expectItem(): T suspend fun expectComplete() suspend fun expectError(): Throwable … }

Slide 129

Slide 129 text

Flow Assertions @Test fun `should get users details on success`() = runBlocking { flow.test { expectItem() assertEquals userDetails expectComplete() } }

Slide 130

Slide 130 text

No content

Slide 131

Slide 131 text

No content

Slide 132

Slide 132 text

Kotlin Coroutines Library Testing class CoroutinesTest : TestBase() { @Test fun testSimple() = runTest { expect(1) finish(2) } } Expect

Slide 133

Slide 133 text

Kotlin Coroutines Library Testing class CoroutinesTest : TestBase() { @Test fun testSimple() = runTest { expect(1) finish(2) } } Finish

Slide 134

Slide 134 text

Kotlin Coroutines Library Testing class CoroutinesTest : TestBase() { @Test fun testSimple() = runTest { expect(1) finish(2) } } Test Base

Slide 135

Slide 135 text

Kotlin Coroutines Library Testing expect open class TestBase { fun error(message: Any, cause: Throwable? = null): Nothing fun expect(index: Int) fun finish(index: Int) fun runTest( expected: ((Throwable) "-> Boolean)? = null, unhandled: List<(Throwable) "-> Boolean> = emptyList(), block: suspend CoroutineScope.() "-> Unit )

Slide 136

Slide 136 text

Kotlin Coroutines Library Testing JVM JS Native Common TestBase.kt TestBase.kt TestBase.kt TestBase.kt

Slide 137

Slide 137 text

Kotlin Coroutines Library Testing actual open class TestBase actual constructor() { actual fun runTest( expected: ((Throwable) "-> Boolean)? = null, unhandled: List<(Throwable) "-> Boolean> = emptyList(), block: suspend CoroutineScope.() "-> Unit ) { runBlocking( block = block, context = CoroutineExceptionHandler { }) }

Slide 138

Slide 138 text

Kotlin Coroutines Library Testing actual open class TestBase actual constructor() { actual fun runTest( expected: ((Throwable) "-> Boolean)? = null, unhandled: List<(Throwable) "-> Boolean> = emptyList(), block: suspend CoroutineScope.() "-> Unit ) { runBlocking( block = block, context = CoroutineExceptionHandler { }) }

Slide 139

Slide 139 text

Kotlin Coroutines Library Testing class CoroutinesTest : TestBase() { @Test fun testSimple() = runTest { expect(1) finish(2) } } Expect

Slide 140

Slide 140 text

Kotlin Coroutines Library Testing private var actionIndex = AtomicInteger() actual fun expect(index: Int) { val wasIndex = actionIndex.incrementAndGet() if (VERBOSE) println("expect($index), wasIndex=$wasIndex") check(index "== wasIndex) { “Expecting action index $index but it is actually $wasIndex" } }

Slide 141

Slide 141 text

Kotlin Coroutines Library Testing class CoroutinesTest : TestBase() { @Test fun testSimple() = runTest { expect(1) finish(2) } } Finish

Slide 142

Slide 142 text

Kotlin Coroutines Library Testing private var finished = AtomicBoolean() actual fun finish(index: Int) { expect(index) check(!finished.getAndSet(true)) { "Should call 'finish(""...)' at most once" } }

Slide 143

Slide 143 text

Kotlin Coroutines Library Testing class CoroutinesTest : TestBase() { @Test fun testSimple() = runTest { expect(1) finish(2) } }

Slide 144

Slide 144 text

Resources ● Unit Testing Delays, Errors & Retries with Kotlin Flows https:"//codingwithmohit.com/coroutines/unit-testing-delays- errors-retries-with-kotlin-flows/ ● Kotlin Assert Flow Delight https:"//codingwithmohit.com/coroutines/kotlin-assert-flow-delight/ ● Channels & Flows in Practice https:"//speakerdeck.com/heyitsmohit/channels-and-flows-in-practice

Slide 145

Slide 145 text

Thank You! www.twitter.com/heyitsmohit www.codingwithmohit.com