Slide 1

Slide 1 text

Untangling Coroutine Testing Márton Braun @zsmb13 Developer Relations Engineer Google

Slide 2

Slide 2 text

Agenda ● Testing suspending functions ● The coroutine test APIs ● Best practices ● Handling the Main dispatcher ● Flows & StateFlows

Slide 3

Slide 3 text

Introduction What’s up with testing coroutines anyway?

Slide 4

Slide 4 text

Introduction

Slide 5

Slide 5 text

Introduction

Slide 6

Slide 6 text

kotlinx.coroutines.test Pre-1.6 APIs 1.6+ APIs

Slide 7

Slide 7 text

kotlinx.coroutines.test Pre-1.6 APIs runBlockingTest TestCoroutineDispatcher TestCoroutineScope pauseDispatcher resumeDispatcher 1.6+ APIs

Slide 8

Slide 8 text

kotlinx.coroutines.test 1.6+ APIs runTest TestDispatcher TestScope TestCoroutineScheduler Pre-1.6 APIs runBlockingTest TestCoroutineDispatcher TestCoroutineScope pauseDispatcher resumeDispatcher

Slide 9

Slide 9 text

kotlinx.coroutines.test 1.6+ APIs runTest TestDispatcher TestScope TestCoroutineScheduler Pre-1.6 APIs runBlockingTest TestCoroutineDispatcher TestCoroutineScope pauseDispatcher resumeDispatcher @Experimental

Slide 10

Slide 10 text

kotlinx.coroutines.test 1.6+ APIs runTest TestDispatcher TestScope TestCoroutineScheduler Pre-1.6 APIs runBlockingTest TestCoroutineDispatcher TestCoroutineScope pauseDispatcher resumeDispatcher @Experimental @Deprecated

Slide 11

Slide 11 text

kotlinx.coroutines.test 1.6+ APIs runTest TestDispatcher TestScope TestCoroutineScheduler Pre-1.6 APIs runBlockingTest TestCoroutineDispatcher TestCoroutineScope pauseDispatcher resumeDispatcher @Experimental @Deprecated @Experimental

Slide 12

Slide 12 text

kotlinx.coroutines.test goo.gle/coroutine-16-migration

Slide 13

Slide 13 text

Testing suspending functions runTest. run.

Slide 14

Slide 14 text

Testing suspending functions suspend fun fetchData(): String { delay(1000L) return "Hello world" }

Slide 15

Slide 15 text

Testing suspending functions suspend fun fetchData(): String { delay(1000L) return "Hello world" } @Test fun dataIsHelloWorld() { val data = fetchData() assertEquals("Hello world", data) }

Slide 16

Slide 16 text

Testing suspending functions suspend fun fetchData(): String { delay(1000L) return "Hello world" } @Test fun dataIsHelloWorld() { val data = fetchData() assertEquals("Hello world", data) }

Slide 17

Slide 17 text

Testing suspending functions suspend fun fetchData(): String { delay(1000L) return "Hello world" } @Test fun dataIsHelloWorld() = runTest { val data = fetchData() assertEquals("Hello world", data) } import kotlinx.coroutines.test.runTest

Slide 18

Slide 18 text

Testing suspending functions suspend fun fetchData(): String { delay(1000L) return "Hello world" } @Test fun dataIsHelloWorld() = runTest { val data = fetchData() assertEquals("Hello world", data) } import kotlinx.coroutines.test.runTest

Slide 19

Slide 19 text

Testing suspending functions suspend fun fetchData(): String { delay(1000L) return "Hello world" } @Test fun dataIsHelloWorld() = runTest { val data = fetchData() assertEquals("Hello world", data) } import kotlinx.coroutines.test.runTest

Slide 20

Slide 20 text

Testing suspending functions suspend fun fetchData(): String { delay(1000L) return "Hello world" } @Test fun dataIsHelloWorld() = runTest { val data = fetchData() assertEquals("Hello world", data) } import kotlinx.coroutines.test.runTest

Slide 21

Slide 21 text

Testing suspending functions suspend fun fetchData(): String { delay(1000L) return "Hello world" } @Test fun dataIsHelloWorld() = runTest { val data = fetchData() assertEquals("Hello world", data) } import kotlinx.coroutines.test.runTest

Slide 22

Slide 22 text

Testing Dispatcher changes suspend fun fetchData(): String = withContext(Dispatchers.IO) { delay(1000L) "Hello world" } @Test fun dataIsHelloWorld() = runTest { val data = fetchData() assertEquals("Hello world", data) } import kotlinx.coroutines.test.runTest

Slide 23

Slide 23 text

Testing Dispatcher changes suspend fun fetchData(): String = withContext(Dispatchers.IO) { delay(1000L) "Hello world" } @Test fun dataIsHelloWorld() = runTest { val data = fetchData() assertEquals("Hello world", data) } import kotlinx.coroutines.test.runTest *

Slide 24

Slide 24 text

Testing Dispatcher changes suspend fun fetchData(): String = withContext(Dispatchers.IO) { delay(1000L) "Hello world" } @Test fun dataIsHelloWorld() = runTest { val data = fetchData() assertEquals("Hello world", data) } Test thread Dispatchers.IO

Slide 25

Slide 25 text

Testing Dispatcher changes suspend fun fetchData(): String = withContext(Dispatchers.IO) { delay(1000L) "Hello world" } @Test fun dataIsHelloWorld() = runTest { val data = fetchData() assertEquals("Hello world", data) } Test thread Dispatchers.IO fetchData()

Slide 26

Slide 26 text

Testing Dispatcher changes suspend fun fetchData(): String = withContext(Dispatchers.IO) { delay(1000L) "Hello world" } @Test fun dataIsHelloWorld() = runTest { val data = fetchData() assertEquals("Hello world", data) } Test thread Dispatchers.IO fetchData()

Slide 27

Slide 27 text

Testing Dispatcher changes suspend fun fetchData(): String = withContext(Dispatchers.IO) { delay(1000L) "Hello world" } @Test fun dataIsHelloWorld() = runTest { val data = fetchData() assertEquals("Hello world", data) } Test thread Dispatchers.IO fetchData() delay()

Slide 28

Slide 28 text

Testing Dispatcher changes suspend fun fetchData(): String = withContext(Dispatchers.IO) { delay(1000L) "Hello world" } @Test fun dataIsHelloWorld() = runTest { val data = fetchData() assertEquals("Hello world", data) } Test thread Dispatchers.IO fetchData() delay()

Slide 29

Slide 29 text

Testing Dispatcher changes suspend fun fetchData(): String = withContext(Dispatchers.IO) { delay(1000L) "Hello world" } @Test fun dataIsHelloWorld() = runTest { val data = fetchData() assertEquals("Hello world", data) } Test thread Dispatchers.IO fetchData() delay() assert()

Slide 30

Slide 30 text

Testing Dispatcher changes suspend fun fetchData(): String = withContext(Dispatchers.IO) { delay(1000L) "Hello world" } @Test fun dataIsHelloWorld() = runTest { val data = fetchData() assertEquals("Hello world", data) } Test thread Dispatchers.IO fetchData() delay() assert()

Slide 31

Slide 31 text

Testing new coroutines

Slide 32

Slide 32 text

Testing new coroutines @Test fun directExample() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals( listOf("Alice", "Bob"), repo.getAllUsers() ) }

Slide 33

Slide 33 text

Testing new coroutines @Test fun directExample() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals( listOf("Alice", "Bob"), repo.getAllUsers() ) }

Slide 34

Slide 34 text

Testing new coroutines class ProfileViewModel : ViewModel() { lateinit var user: User fun initialize() { viewModelScope.launch { user = fetchUser() } } } @Test fun directExample() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals( listOf("Alice", "Bob"), repo.getAllUsers() ) }

Slide 35

Slide 35 text

Testing new coroutines class ProfileViewModel : ViewModel() { lateinit var user: User fun initialize() { viewModelScope.launch { user = fetchUser() } } } @Test fun indirectExample() = runTest { val viewModel = ProfileViewModel() viewModel.initialize() assertEquals("Sam", viewModel.user.name) } @Test fun directExample() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals( listOf("Alice", "Bob"), repo.getAllUsers() ) }

Slide 36

Slide 36 text

Testing new coroutines class ProfileViewModel : ViewModel() { lateinit var user: User fun initialize() { viewModelScope.launch { user = fetchUser() } } } @Test fun indirectExample() = runTest { val viewModel = ProfileViewModel() viewModel.initialize() assertEquals("Sam", viewModel.user.name) } @Test fun directExample() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals( listOf("Alice", "Bob"), repo.getAllUsers() ) }

Slide 37

Slide 37 text

Testing new coroutines class ProfileViewModel : ViewModel() { lateinit var user: User fun initialize() { viewModelScope.launch { user = fetchUser() } } } @Test fun indirectExample() = runTest { val viewModel = ProfileViewModel() viewModel.initialize() assertEquals("Sam", viewModel.user.name) } @Test fun directExample() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals( listOf("Alice", "Bob"), repo.getAllUsers() ) }

Slide 38

Slide 38 text

The coroutine test APIs The latest and greatest in kotlinx.coroutines.test

Slide 39

Slide 39 text

Test APIs runTest

Slide 40

Slide 40 text

Test APIs runTest TestScope

Slide 41

Slide 41 text

Test APIs runTest TestDispatcher TestScope

Slide 42

Slide 42 text

Test APIs runTest TestDispatcher TestCoroutineScheduler TestScope

Slide 43

Slide 43 text

Test APIs runTest TestDispatcher TestCoroutineScheduler TestScope TestDispatcher TestDispatcher

Slide 44

Slide 44 text

Test APIs runTest TestCoroutineScheduler TestScope TestDispatcher TestDispatcher All TestDispatchers must share the same scheduler TestDispatcher

Slide 45

Slide 45 text

Test APIs TestDispatcher TestCoroutineScheduler

Slide 46

Slide 46 text

Test APIs TestCoroutineScheduler StandardTestDispatcher UnconfinedTestDispatcher TestDispatcher

Slide 47

Slide 47 text

StandardTestDispatcher

Slide 48

Slide 48 text

● Queues up coroutines on the scheduler StandardTestDispatcher

Slide 49

Slide 49 text

● Queues up coroutines on the scheduler ● You need to advance those coroutines manually StandardTestDispatcher

Slide 50

Slide 50 text

● Queues up coroutines on the scheduler ● You need to advance those coroutines manually ● runTest uses a StandardTestDispatcher by default StandardTestDispatcher runTest StandardTestDispatcher TestScope

Slide 51

Slide 51 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) }

Slide 52

Slide 52 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } this: TestScope

Slide 53

Slide 53 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) }

Slide 54

Slide 54 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } UserRepo()

Slide 55

Slide 55 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } UserRepo() reg("Alice")

Slide 56

Slide 56 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } UserRepo() reg("Bob") reg("Alice")

Slide 57

Slide 57 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } UserRepo() assert() reg("Bob") reg("Alice")

Slide 58

Slide 58 text

StandardTestDispatcher UserRepo() assert() @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } reg("Bob") reg("Alice")

Slide 59

Slide 59 text

● You need to advance those coroutines manually StandardTestDispatcher

Slide 60

Slide 60 text

● You need to advance those coroutines manually StandardTestDispatcher 80 ms 90 ms 100 ms 500 ms 750 ms

Slide 61

Slide 61 text

● You need to advance those coroutines manually StandardTestDispatcher ● runCurrent() 80 ms 90 ms 100 ms 500 ms 750 ms

Slide 62

Slide 62 text

● You need to advance those coroutines manually StandardTestDispatcher ● runCurrent() 80 ms 90 ms 100 ms 500 ms 750 ms

Slide 63

Slide 63 text

● You need to advance those coroutines manually StandardTestDispatcher ● runCurrent() ● advanceTimeBy(delayTimeMillis: Long) 80 ms 90 ms 100 ms 500 ms 750 ms

Slide 64

Slide 64 text

● You need to advance those coroutines manually StandardTestDispatcher 80 ms 90 ms 100 ms 500 ms 750 ms ● runCurrent() ● advanceTimeBy(delayTimeMillis = 100)

Slide 65

Slide 65 text

● You need to advance those coroutines manually StandardTestDispatcher ● runCurrent() ● advanceTimeBy(delayTimeMillis = 100) 80 ms 90 ms 100 ms 500 ms 750 ms

Slide 66

Slide 66 text

● You need to advance those coroutines manually StandardTestDispatcher ● runCurrent() ● advanceTimeBy(delayTimeMillis: Long) ● advanceUntilIdle() 80 ms 90 ms 100 ms 500 ms 750 ms

Slide 67

Slide 67 text

● You need to advance those coroutines manually StandardTestDispatcher ● runCurrent() ● advanceTimeBy(delayTimeMillis: Long) ● advanceUntilIdle() 80 ms 90 ms 100 ms 500 ms 750 ms

Slide 68

Slide 68 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) }

Slide 69

Slide 69 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } advanceUntilIdle() assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) }

Slide 70

Slide 70 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } advanceUntilIdle() assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) }

Slide 71

Slide 71 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } advanceUntilIdle() assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } UserRepo()

Slide 72

Slide 72 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } advanceUntilIdle() assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } UserRepo() reg("Alice")

Slide 73

Slide 73 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } advanceUntilIdle() assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } UserRepo() reg("Bob") reg("Alice")

Slide 74

Slide 74 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } advanceUntilIdle() assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } UserRepo() reg("Alice") reg("Bob")

Slide 75

Slide 75 text

Idle StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } advanceUntilIdle() assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } UserRepo() reg("Alice") reg("Bob")

Slide 76

Slide 76 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } advanceUntilIdle() assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } UserRepo() reg("Alice") reg("Bob") Idle

Slide 77

Slide 77 text

StandardTestDispatcher UserRepo() reg("Alice") reg("Bob") @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } advanceUntilIdle() assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) }

Slide 78

Slide 78 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } advanceUntilIdle() assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } UserRepo() reg("Alice") reg("Bob") assert()

Slide 79

Slide 79 text

StandardTestDispatcher @Test fun standardTest() = runTest { val repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } advanceUntilIdle() assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } UserRepo() reg("Alice") reg("Bob") assert()

Slide 80

Slide 80 text

UnconfinedTestDispatcher

Slide 81

Slide 81 text

UnconfinedTestDispatcher ● Starts new coroutines eagerly (like runBlockingTest)

Slide 82

Slide 82 text

UnconfinedTestDispatcher ● Starts new coroutines eagerly (like runBlockingTest) ● Can be a good choice for simple tests

Slide 83

Slide 83 text

UnconfinedTestDispatcher ● Starts new coroutines eagerly (like runBlockingTest) ● Can be a good choice for simple tests ● Does not emulate real concurrency

Slide 84

Slide 84 text

UnconfinedTestDispatcher @Test fun unconfinedTest() = runTest(UnconfinedTestDispatcher()) { val userRepo = UserRepository() launch { userRepo.register("Alice") } launch { userRepo.register("Bob") } assertEquals(listOf("Alice", "Bob"), userRepo.getAllUsers()) }

Slide 85

Slide 85 text

UnconfinedTestDispatcher @Test fun unconfinedTest() = runTest(UnconfinedTestDispatcher()) { val userRepo = UserRepository() launch { userRepo.register("Alice") } launch { userRepo.register("Bob") } assertEquals(listOf("Alice", "Bob"), userRepo.getAllUsers()) }

Slide 86

Slide 86 text

UnconfinedTestDispatcher @Test fun unconfinedTest() = runTest(UnconfinedTestDispatcher()) { val userRepo = UserRepository() launch { userRepo.register("Alice") } launch { userRepo.register("Bob") } assertEquals(listOf("Alice", "Bob"), userRepo.getAllUsers()) } this: TestScope

Slide 87

Slide 87 text

UnconfinedTestDispatcher @Test fun unconfinedTest() = runTest(UnconfinedTestDispatcher()) { val userRepo = UserRepository() launch { userRepo.register("Alice") } launch { userRepo.register("Bob") } assertEquals(listOf("Alice", "Bob"), userRepo.getAllUsers()) } UserRepo()

Slide 88

Slide 88 text

UnconfinedTestDispatcher @Test fun unconfinedTest() = runTest(UnconfinedTestDispatcher()) { val userRepo = UserRepository() launch { userRepo.register("Alice") } launch { userRepo.register("Bob") } assertEquals(listOf("Alice", "Bob"), userRepo.getAllUsers()) } UserRepo() reg("Alice")

Slide 89

Slide 89 text

UnconfinedTestDispatcher @Test fun unconfinedTest() = runTest(UnconfinedTestDispatcher()) { val userRepo = UserRepository() launch { userRepo.register("Alice") } launch { userRepo.register("Bob") } assertEquals(listOf("Alice", "Bob"), userRepo.getAllUsers()) } UserRepo() reg("Alice") reg("Bob")

Slide 90

Slide 90 text

UnconfinedTestDispatcher @Test fun unconfinedTest() = runTest(UnconfinedTestDispatcher()) { val userRepo = UserRepository() launch { userRepo.register("Alice") } launch { userRepo.register("Bob") } assertEquals(listOf("Alice", "Bob"), userRepo.getAllUsers()) } UserRepo() reg("Alice") reg("Bob") assert()

Slide 91

Slide 91 text

UnconfinedTestDispatcher @Test fun unconfinedTest() = runTest(UnconfinedTestDispatcher()) { val userRepo = UserRepository() launch { userRepo.register("Alice") } launch { userRepo.register("Bob") } assertEquals(listOf("Alice", "Bob"), userRepo.getAllUsers()) } UserRepo() reg("Alice") reg("Bob") assert()

Slide 92

Slide 92 text

TestDispatchers StandardTestDispatcher Queues up new coroutines Use by default UnconfinedTestDispatcher Starts new coroutines eagerly Use selectively

Slide 93

Slide 93 text

TestDispatchers Queues up new coroutines Use by default Starts new coroutines eagerly Use selectively • While migrating tests from old APIs • As the Main dispatcher • For coroutines that collect values StandardTestDispatcher UnconfinedTestDispatcher

Slide 94

Slide 94 text

Injecting dispatchers Something something heat exchangers

Slide 95

Slide 95 text

Injecting dispatchers class Repository(private val database: Database) { private val scope = CoroutineScope(Dispatchers.IO) fun initialize() { scope.launch { database.populate() } } suspend fun fetchData(): String = withContext(Dispatchers.IO) { database.read() } }

Slide 96

Slide 96 text

Injecting dispatchers class Repository(private val database: Database) { private val scope = CoroutineScope(Dispatchers.IO) fun initialize() { scope.launch { database.populate() } } suspend fun fetchData(): String = withContext(Dispatchers.IO) { database.read() } }

Slide 97

Slide 97 text

Injecting dispatchers class Repository(private val database: Database) { private val scope = CoroutineScope(Dispatchers.IO) fun initialize() { scope.launch { database.populate() } } suspend fun fetchData(): String = withContext(Dispatchers.IO) { database.read() } }

Slide 98

Slide 98 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository(FakeDatabase()) repository.initialize() val data = repository.fetchData() assertEquals("Hello world", data) }

Slide 99

Slide 99 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository(FakeDatabase()) repository.initialize() val data = repository.fetchData() assertEquals("Hello world", data) } Test thread Dispatchers.IO

Slide 100

Slide 100 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository(FakeDatabase()) repository.initialize() val data = repository.fetchData() assertEquals("Hello world", data) } Repo(FakeDb()) Test thread Dispatchers.IO

Slide 101

Slide 101 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository(FakeDatabase()) repository.initialize() val data = repository.fetchData() assertEquals("Hello world", data) } Repo(FakeDb()) Test thread Dispatchers.IO db.populate() fun initialize() { scope.launch { database.populate() } }

Slide 102

Slide 102 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository(FakeDatabase()) repository.initialize() val data = repository.fetchData() assertEquals("Hello world", data) } Repo(FakeDb()) Test thread Dispatchers.IO db.read() db.populate() suspend fun fetchData() = withContext(Dispatchers.IO) { database.read() }

Slide 103

Slide 103 text

assert() Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository(FakeDatabase()) repository.initialize() val data = repository.fetchData() assertEquals("Hello world", data) } Repo(FakeDb()) Test thread Dispatchers.IO db.read() db.populate()

Slide 104

Slide 104 text

assert() Injecting dispatchers Repo(FakeDb()) Test thread Dispatchers.IO db.read() db.populate() @Test fun repoTest() = runTest { val repository = Repository(FakeDatabase()) repository.initialize() val data = repository.fetchData() assertEquals("Hello world", data) }

Slide 105

Slide 105 text

Injecting dispatchers Repo(FakeDb()) Test thread Dispatchers.IO db.read() db.populate() assert() @Test fun repoTest() = runTest { val repository = Repository(FakeDatabase()) repository.initialize() val data = repository.fetchData() assertEquals("Hello world", data) }

Slide 106

Slide 106 text

Injecting dispatchers Repo(FakeDb()) Test thread Dispatchers.IO db.read() db.populate() assert() @Test fun repoTest() = runTest { val repository = Repository(FakeDatabase()) repository.initialize() val data = repository.fetchData() assertEquals("Hello world", data) }

Slide 107

Slide 107 text

, ioDispatcher ioDispatcher Injecting dispatchers class Repository( Dispatchers.IO) fun initialize() { scope.launch { database.populate() } } suspend fun fetchData(): String = withContext( ) { database.read() } } private val database: Database) { private val scope = CoroutineScope( Dispatchers.IO

Slide 108

Slide 108 text

Dispatchers.IO Injecting dispatchers class Repository( private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, ioDispatcher) fun initialize() { scope.launch { database.populate() } } suspend fun fetchData(): String = withContext( ) { database.read() } } private val database: Database ) { private val scope = CoroutineScope( ioDispatcher ,

Slide 109

Slide 109 text

Dispatchers.IO Injecting dispatchers class Repository( private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, ioDispatcher) fun initialize() { scope.launch { database.populate() } } suspend fun fetchData(): String = withContext( ) { database.read() } } private val database: Database ) { private val scope = CoroutineScope( ioDispatcher ,

Slide 110

Slide 110 text

FakeDatabase(), @Test fun repoTest() = runTest { val repository = Repository( ) repository.initialize() val data = repository.fetchData() assertEquals("Hello world", data) } Injecting dispatchers

Slide 111

Slide 111 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository( database = , ioDispatcher = StandardTestDispatcher(testScheduler), ) repository.initialize() advanceUntilIdle() val data = repository.fetchData() assertEquals("Hello world", data) } FakeDatabase()

Slide 112

Slide 112 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository( database = FakeDatabase(), ioDispatcher = StandardTestDispatcher(testScheduler), ) repository.initialize() advanceUntilIdle() val data = repository.fetchData() assertEquals("Hello world", data) } this: TestScope

Slide 113

Slide 113 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository( database = FakeDatabase(), ioDispatcher = StandardTestDispatcher(testScheduler), ) repository.initialize() advanceUntilIdle() val data = repository.fetchData() assertEquals("Hello world", data) }

Slide 114

Slide 114 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository( database = FakeDatabase(), ioDispatcher = StandardTestDispatcher(testScheduler), ) repository.initialize() advanceUntilIdle() val data = repository.fetchData() assertEquals("Hello world", data) } Repo(...)

Slide 115

Slide 115 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository( database = FakeDatabase(), ioDispatcher = StandardTestDispatcher(testScheduler), ) repository.initialize() advanceUntilIdle() val data = repository.fetchData() assertEquals("Hello world", data) } fun initialize() { scope.launch { database.populate() } } Repo(...)

Slide 116

Slide 116 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository( database = FakeDatabase(), ioDispatcher = StandardTestDispatcher(testScheduler), ) repository.initialize() advanceUntilIdle() val data = repository.fetchData() assertEquals("Hello world", data) } Repo(...) db.populate() fun initialize() { scope.launch { database.populate() } }

Slide 117

Slide 117 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository( database = FakeDatabase(), ioDispatcher = StandardTestDispatcher(testScheduler), ) repository.initialize() advanceUntilIdle() val data = repository.fetchData() assertEquals("Hello world", data) } Repo(...) db.populate()

Slide 118

Slide 118 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository( database = FakeDatabase(), ioDispatcher = StandardTestDispatcher(testScheduler), ) repository.initialize() advanceUntilIdle() val data = repository.fetchData() assertEquals("Hello world", data) } Repo(...) db.populate()

Slide 119

Slide 119 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository( database = FakeDatabase(), ioDispatcher = StandardTestDispatcher(testScheduler), ) repository.initialize() advanceUntilIdle() val data = repository.fetchData() assertEquals("Hello world", data) } Repo(...) db.populate() db.read() suspend fun fetchData() = withContext(ioDispatcher) { database.read() }

Slide 120

Slide 120 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository( database = FakeDatabase(), ioDispatcher = StandardTestDispatcher(testScheduler), ) repository.initialize() advanceUntilIdle() val data = repository.fetchData() assertEquals("Hello world", data) } Repo(...) db.populate() db.read() assert()

Slide 121

Slide 121 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository( database = FakeDatabase(), ioDispatcher = StandardTestDispatcher(testScheduler), ) repository.initialize() advanceUntilIdle() val data = repository.fetchData() assertEquals("Hello world", data) } fun initialize() { scope.launch { database.populate() } } This is a bad API, don’t do this

Slide 122

Slide 122 text

Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository( database = FakeDatabase(), ioDispatcher = StandardTestDispatcher(testScheduler), ) repository.initialize().await(). val data = repository.fetchData() assertEquals("Hello world", data) } fun initialize(): Deferred { return scope.async { } } database.populate()

Slide 123

Slide 123 text

suspend fun initialize() { } Injecting dispatchers @Test fun repoTest() = runTest { val repository = Repository( database = FakeDatabase(), ioDispatcher = StandardTestDispatcher(testScheduler), ) repository.initialize() val data = repository.fetchData() assertEquals("Hello world", data) } database.populate()

Slide 124

Slide 124 text

Handling the Main dispatcher A UI thread without a UI

Slide 125

Slide 125 text

Handling the Main dispatcher class HomeViewModel : ViewModel() { private val _message = MutableStateFlow("") val message: StateFlow get() = _message fun loadMessage() { viewModelScope.launch { _message.value = "Greetings!" } } }

Slide 126

Slide 126 text

Handling the Main dispatcher class HomeViewModel : ViewModel() { private val _message = MutableStateFlow("") val message: StateFlow get() = _message fun loadMessage() { viewModelScope.launch { _message.value = "Greetings!" } } }

Slide 127

Slide 127 text

Handling the Main dispatcher } val viewModel = HomeViewModel() viewModel.loadMessage() assertEquals("Greetings!", viewModel.message.value) @Test fun testGreeting() = runTest {

Slide 128

Slide 128 text

Handling the Main dispatcher } val viewModel = HomeViewModel() viewModel.loadMessage() assertEquals("Greetings!", viewModel.message.value) @Test fun testGreeting() = runTest { java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used

Slide 129

Slide 129 text

Handling the Main dispatcher } val viewModel = HomeViewModel() viewModel.loadMessage() assertEquals("Greetings!", viewModel.message.value) @Test fun testGreeting() = runTest { java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used

Slide 130

Slide 130 text

Handling the Main dispatcher val testDispatcher = UnconfinedTestDispatcher(testScheduler) Dispatchers.setMain(testDispatcher) val viewModel = HomeViewModel() viewModel.loadMessage() assertEquals("Greetings!", viewModel.message.value) } @Test fun testGreeting() = runTest { java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used

Slide 131

Slide 131 text

Handling the Main dispatcher val testDispatcher = UnconfinedTestDispatcher(testScheduler) Dispatchers.setMain(testDispatcher) val viewModel = HomeViewModel() viewModel.loadMessage() assertEquals("Greetings!", viewModel.message.value) } @Test fun testGreeting() = runTest { java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used

Slide 132

Slide 132 text

java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used Handling the Main dispatcher val testDispatcher = UnconfinedTestDispatcher(testScheduler) Dispatchers.setMain(testDispatcher) try { } finally { Dispatchers.resetMain() } val viewModel = HomeViewModel() viewModel.loadMessage() assertEquals("Greetings!", viewModel.message.value) } @Test fun testGreeting() = runTest {

Slide 133

Slide 133 text

Handling the Main dispatcher @Test fun testGreeting() = runTest { val testDispatcher = UnconfinedTestDispatcher(testScheduler) Dispatchers.setMain(testDispatcher) try { val viewModel = HomeViewModel() viewModel.loadMessage() assertEquals("Greetings!", viewModel.message.value) } finally { Dispatchers.resetMain() } }

Slide 134

Slide 134 text

Handling the Main dispatcher @Test fun testGreeting() = runTest { val testDispatcher = UnconfinedTestDispatcher(testScheduler) Dispatchers.setMain(testDispatcher) try { val viewModel = HomeViewModel() viewModel.loadMessage() assertEquals("Greetings!", viewModel.message.value) } finally { Dispatchers.resetMain() } } fun loadMessage() { viewModelScope.launch { _message.value = "Greetings!" } }

Slide 135

Slide 135 text

Handling the Main dispatcher @Test fun testGreeting() = runTest { val testDispatcher = UnconfinedTestDispatcher(testScheduler) try { val viewModel = HomeViewModel() viewModel.loadMessage() assertEquals("Greetings!", viewModel.message.value) } finally { } } Dispatchers.setMain(testDispatcher) Dispatchers.resetMain()

Slide 136

Slide 136 text

Handling the Main dispatcher class MainDispatcherRule( val testDispatcher: TestDispatcher = UnconfinedTestDispatcher(), ) : TestWatcher() { override fun starting(description: Description) { } override fun finished(description: Description) { } } Dispatchers.setMain(testDispatcher) Dispatchers.resetMain()

Slide 137

Slide 137 text

Handling the Main dispatcher class HomeViewModelTestUsingRule { @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun testGreeting() = runTest { val viewModel = HomeViewModel() viewModel.loadMessage() assertEquals("Greetings!", viewModel.message.value) } }

Slide 138

Slide 138 text

class HomeViewModelTestUsingRule { @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun testGreeting() = runTest { Handling the Main dispatcher val viewModel = HomeViewModel() viewModel.loadMessage() assertEquals("Greetings!", viewModel.message.value) } }

Slide 139

Slide 139 text

Handling the Main dispatcher val viewModel = HomeViewModel() viewModel.loadMessage() assertEquals("Greetings!", viewModel.message.value) If you replace the Main dispatcher with a TestDispatcher, all new TestDispatchers will automatically share its scheduler class HomeViewModelTestUsingRule { @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun testGreeting() = runTest { } }

Slide 140

Slide 140 text

Handling the Main dispatcher val unconfinedDispatcher = UnconfinedTestDispatcher() val standardDispatcher = StandardTestDispatcher() If you replace the Main dispatcher with a TestDispatcher, all new TestDispatchers will automatically share its scheduler class HomeViewModelTestUsingRule { @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun testGreeting() = runTest { } }

Slide 141

Slide 141 text

Flows Suspenseful streams

Slide 142

Slide 142 text

Flows interface DataSource { fun counts(): Flow } class Repository(private val dataSource: DataSource) { fun scores(): Flow { return dataSource.counts().map { it * 10 } } }

Slide 143

Slide 143 text

Flows Test Repository Fake Data Source

Slide 144

Slide 144 text

Flows interface DataSource { fun counts(): Flow } class Repository(private val dataSource: DataSource) { fun scores(): Flow { return dataSource.counts().map { it * 10 } } }

Slide 145

Slide 145 text

Flows interface DataSource { fun counts(): Flow } class Repository(private val dataSource: DataSource) { fun scores(): Flow { return dataSource.counts().map { it * 10 } } } class ColdFakeDataSource : DataSource { override fun counts(): Flow { return flowOf(1, 2, 3, 4) } }

Slide 146

Slide 146 text

Flows @Test fun useTerminalOperators() = runTest { val repository = Repository(ColdFakeDataSource()) }

Slide 147

Slide 147 text

Flows @Test fun useTerminalOperators() = runTest { val repository = Repository(ColdFakeDataSource()) val first = repository.scores().first() assertEquals(10, first) }

Slide 148

Slide 148 text

Flows @Test fun useTerminalOperators() = runTest { val repository = Repository(ColdFakeDataSource()) val first = repository.scores().first() assertEquals(10, first) val values = repository.scores().toList() assertEquals(10, values[0]) assertEquals(20, values[1]) assertEquals(4, values.size) }

Slide 149

Slide 149 text

Flows @Test fun useTerminalOperators() = runTest { val repository = Repository(ColdFakeDataSource()) val first = repository.scores().first() assertEquals(10, first) val values = repository.scores().toList() assertEquals(10, values[0]) assertEquals(20, values[1]) assertEquals(4, values.size) val someValues = repository.scores().take(2).toList() assertEquals(10, someValues[0]) assertEquals(20, someValues[1]) }

Slide 150

Slide 150 text

Flows class HotFakeDataSource : DataSource { private val flow = MutableSharedFlow() suspend fun emit(value: Int) = flow.emit(value) override fun counts(): Flow = flow }

Slide 151

Slide 151 text

Flows class HotFakeDataSource : DataSource { private val flow = MutableSharedFlow() suspend fun emit(value: Int) = flow.emit(value) override fun counts(): Flow = flow }

Slide 152

Slide 152 text

Flows class HotFakeDataSource : DataSource { private val flow = MutableSharedFlow() suspend fun emit(value: Int) = flow.emit(value) override fun counts(): Flow = flow }

Slide 153

Slide 153 text

Flows @Test fun continuouslyCollect() = runTest { val dataSource = HotFakeDataSource() val repository = Repository(dataSource) }

Slide 154

Slide 154 text

Flows @Test fun continuouslyCollect() = runTest { val dataSource = HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf() }

Slide 155

Slide 155 text

Flows launch(UnconfinedTestDispatcher()) { collect { values += it } } @Test fun continuouslyCollect() = runTest { val dataSource = HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf() } repository.scores().

Slide 156

Slide 156 text

Flows launch(UnconfinedTestDispatcher()) { toList(values) } repository.scores(). @Test fun continuouslyCollect() = runTest { val dataSource = HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf() }

Slide 157

Slide 157 text

Flows launch(UnconfinedTestDispatcher()) { } } @Test fun continuouslyCollect() = runTest { val dataSource = HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf() dataSource.emit(1) assertEquals(10, values[0]) repository.scores().toList(values) val collectJob =

Slide 158

Slide 158 text

Flows val collectJob = launch(UnconfinedTestDispatcher()) { } } collectJob.cancel() @Test fun continuouslyCollect() = runTest { val dataSource = HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf() dataSource.emit(1) assertEquals(10, values[0]) repository.scores().toList(values)

Slide 159

Slide 159 text

Flows val collectJob = launch(UnconfinedTestDispatcher()) { repository.scores().toList(values) } dataSource.emit(1) assertEquals(10, values[0]) dataSource.emit(2) dataSource.emit(3) assertEquals(30, values.last()) assertEquals(3, values.size) } collectJob.cancel() @Test fun continuouslyCollect() = runTest { val dataSource = HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf()

Slide 160

Slide 160 text

Flows with Turbine

Slide 161

Slide 161 text

StateFlows Look! It’s a stream! It’s a state holder!

Slide 162

Slide 162 text

Stream StateFlows State holder Source: Manuel Vivo

Slide 163

Slide 163 text

interface MyRepository { fun scores(): Flow } class MyViewModel(private val myRepository: MyRepository) : ViewModel() { private val _data = MutableStateFlow(0) val data: StateFlow = _data.asStateFlow() fun initialize() { viewModelScope.launch { myRepository.scores().collect { score -> _data.value = score } } } } StateFlows

Slide 164

Slide 164 text

interface MyRepository { fun scores(): Flow } class MyViewModel(private val myRepository: MyRepository) : ViewModel() { private val _data = MutableStateFlow(0) val data: StateFlow = _data.asStateFlow() fun initialize() { viewModelScope.launch { myRepository.scores().collect { score -> _data.value = score } } } } StateFlows

Slide 165

Slide 165 text

interface MyRepository { fun scores(): Flow } class MyViewModel(private val myRepository: MyRepository) : ViewModel() { private val _data = MutableStateFlow(0) val data: StateFlow = _data.asStateFlow() fun initialize() { viewModelScope.launch { myRepository.scores().collect { score -> _data.value = score } } } } StateFlows

Slide 166

Slide 166 text

interface MyRepository { fun scores(): Flow } class MyViewModel(private val myRepository: MyRepository) : ViewModel() { private val _data = MutableStateFlow(0) val data: StateFlow = _data.asStateFlow() fun initialize() { viewModelScope.launch { myRepository.scores().collect { score -> _data.value = score } } } } StateFlows

Slide 167

Slide 167 text

StateFlows Test ViewModel Fake Repository

Slide 168

Slide 168 text

StateFlows class HotFakeRepository : MyRepository { private val flow = MutableSharedFlow() suspend fun emit(value: Int) = flow.emit(value) override fun scores(): Flow = flow }

Slide 169

Slide 169 text

@get:Rule val mainDispatcherRule = MainDispatcherRule() StateFlows @Test fun testHotFakeRepository() = runTest { val fakeRepository = HotFakeRepository() val viewModel = MyViewModel(fakeRepository) }

Slide 170

Slide 170 text

StateFlows @Test fun testHotFakeRepository() = runTest { val fakeRepository = HotFakeRepository() val viewModel = MyViewModel(fakeRepository) }

Slide 171

Slide 171 text

StateFlows @Test fun testHotFakeRepository() = runTest { val fakeRepository = HotFakeRepository() val viewModel = MyViewModel(fakeRepository) assertEquals(0, viewModel.data.value) }

Slide 172

Slide 172 text

StateFlows @Test fun testHotFakeRepository() = runTest { val fakeRepository = HotFakeRepository() val viewModel = MyViewModel(fakeRepository) assertEquals(0, viewModel.data.value) viewModel.initialize() } fun initialize() { viewModelScope.launch { myRepository.scores().collect { score -> _data.value = score } } }

Slide 173

Slide 173 text

StateFlows @Test fun testHotFakeRepository() = runTest { val fakeRepository = HotFakeRepository() val viewModel = MyViewModel(fakeRepository) assertEquals(0, viewModel.data.value) viewModel.initialize() fakeRepository.emit(1) assertEquals(1, viewModel.data.value) }

Slide 174

Slide 174 text

StateFlows @Test fun testHotFakeRepository() = runTest { val fakeRepository = HotFakeRepository() val viewModel = MyViewModel(fakeRepository) assertEquals(0, viewModel.data.value) viewModel.initialize() fakeRepository.emit(1) assertEquals(1, viewModel.data.value) fakeRepository.emit(2) fakeRepository.emit(3) assertEquals(3, viewModel.data.value) }

Slide 175

Slide 175 text

StateFlows @Test fun testHotFakeRepository() = runTest { val fakeRepository = HotFakeRepository() val viewModel = MyViewModel(fakeRepository) assertEquals(0, viewModel.data.value) viewModel.initialize() fakeRepository.emit(1) assertEquals(1, viewModel.data.value) fakeRepository.emit(2) fakeRepository.emit(3) assertEquals(3, viewModel.data.value) }

Slide 176

Slide 176 text

StateFlows @Test fun testHotFakeRepository() = runTest { val fakeRepository = HotFakeRepository() val viewModel = MyViewModel(fakeRepository) assertEquals(0, viewModel.data.value) viewModel.initialize() fakeRepository.emit(1) assertEquals(1, viewModel.data.value) fakeRepository.emit(2) fakeRepository.emit(3) assertEquals(3, viewModel.data.value) }

Slide 177

Slide 177 text

StateFlows with stateIn private val _data = MutableStateFlow(0) _data.asStateFlow() fun initialize() { .launch { .collect { count -> _data.value = count } } } myRepository: MyRepository myRepository.scores() class MyViewModel( ) : ViewModel() { private val viewModelScope val data: StateFlow = }

Slide 178

Slide 178 text

StateFlows with stateIn myRepository: MyRepository myRepository.scores() .stateIn( , SharingStarted.WhileSubscribed(5000), 0) class MyViewModel( ) : ViewModel() { viewModelScope val data: StateFlow = }

Slide 179

Slide 179 text

StateFlows with stateIn @Test fun testLazilySharingViewModel() = runTest { val fakeRepository = HotFakeRepository() val viewModel = MyViewModel(fakeRepository) assertEquals(0, viewModel.data.value) fakeRepository.emit(1) assertEquals(1, viewModel.data.value) }

Slide 180

Slide 180 text

StateFlows with stateIn @Test fun testLazilySharingViewModel() = runTest { val fakeRepository = HotFakeRepository() val viewModel = MyViewModel(fakeRepository) assertEquals(0, viewModel.data.value) fakeRepository.emit(1) assertEquals(1, viewModel.data.value) }

Slide 181

Slide 181 text

StateFlows with stateIn class MyViewModel( myRepository: MyRepository ) : ViewModel() { val data: StateFlow = myRepository.scores() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 0) }

Slide 182

Slide 182 text

StateFlows with stateIn class MyViewModel( myRepository: MyRepository ) : ViewModel() { val data: StateFlow = myRepository.scores() .stateIn(viewModelScope, , 0) } Test ViewModel Fake Repository SharingStarted.WhileSubscribed(5000)

Slide 183

Slide 183 text

StateFlows with stateIn class MyViewModel( myRepository: MyRepository ) : ViewModel() { val data: StateFlow = myRepository.scores() .stateIn(viewModelScope, , 0) } Test ViewModel Fake Repository SharingStarted.WhileSubscribed(5000)

Slide 184

Slide 184 text

StateFlows with stateIn class MyViewModel( myRepository: MyRepository ) : ViewModel() { val data: StateFlow = myRepository.scores() .stateIn(viewModelScope, , 0) } Test ViewModel Fake Repository SharingStarted.WhileSubscribed(5000)

Slide 185

Slide 185 text

StateFlows with stateIn class MyViewModel( myRepository: MyRepository ) : ViewModel() { val data: StateFlow = myRepository.scores() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 0) } Test ViewModel Fake Repository

Slide 186

Slide 186 text

StateFlows with stateIn class MyViewModel( myRepository: MyRepository ) : ViewModel() { val data: StateFlow = myRepository.scores() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 0) } Test ViewModel Fake Repository

Slide 187

Slide 187 text

StateFlows with stateIn class MyViewModel( myRepository: MyRepository ) : ViewModel() { val data: StateFlow = myRepository.scores() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 0) } Test ViewModel Fake Repository

Slide 188

Slide 188 text

StateFlows with stateIn class MyViewModel( myRepository: MyRepository ) : ViewModel() { val data: StateFlow = myRepository.scores() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 0) } Test ViewModel Fake Repository

Slide 189

Slide 189 text

StateFlows with stateIn class MyViewModel( myRepository: MyRepository ) : ViewModel() { val data: StateFlow = myRepository.scores() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 0) } SharingStarted.Lazily Test ViewModel Fake Repository

Slide 190

Slide 190 text

StateFlows with stateIn @Test fun testLazilySharingViewModel() = runTest { val fakeRepository = HotFakeRepository() val viewModel = MyViewModel(fakeRepository) assertEquals(0, viewModel.data.value) fakeRepository.emit(1) assertEquals(1, viewModel.data.value) }

Slide 191

Slide 191 text

StateFlows with stateIn val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.data.collect() } assertEquals(0, viewModel.data.value) fakeRepository.emit(1) assertEquals(1, viewModel.data.value) } collectJob.cancel() @Test fun testLazilySharingViewModel() = runTest { val fakeRepository = HotFakeRepository() val viewModel = MyViewModel(fakeRepository)

Slide 192

Slide 192 text

Summary What did we learn today?

Slide 193

Slide 193 text

Summary ● Use runTest for tests with coroutines ● Inject dispatchers into your classes to make them testable ● Create TestDispatchers as needed, always share a single scheduler ● Replace the Main dispatcher in unit tests (also simplifies sharing!)

Slide 194

Slide 194 text

Resources ● goo.gle/coroutine-test-guide ● goo.gle/flow-test-guide ● goo.gle/coroutine-16-migration ● github.com/cashapp/turbine NEW!

Slide 195

Slide 195 text

Thank You! Márton Braun @zsmb13 Untangling Coroutine Testing