Slide 1

Slide 1 text

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

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-test-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 TestDispatcher TestCoroutineScheduler TestScope TestDispatcher TestDispatcher All TestDispatchers must share the same scheduler

Slide 45

Slide 45 text

Test APIs TestDispatcher TestCoroutineScheduler

Slide 46

Slide 46 text

Test APIs TestDispatcher TestCoroutineScheduler StandardTestDispatcher UnconfinedTestDispatcher

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("Alice") reg("Bob")

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("Alice") reg("Bob")

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("Alice") reg("Bob")

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 80 ms 90 ms 100 ms 500 ms 750 ms ● runCurrent()

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 ● runCurrent() ● advanceTimeBy(delayTimeMillis: Long) 80 ms 90 ms 100 ms 500 ms 750 ms

Slide 65

Slide 65 text

● You need to advance those coroutines manually StandardTestDispatcher ● runCurrent() ● advanceTimeBy(delayTimeMillis: Long) 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("Alice") reg("Bob")

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

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")

Slide 77

Slide 77 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 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

UnconfinedTestDispatcher

Slide 80

Slide 80 text

UnconfinedTestDispatcher ● Starts new coroutines eagerly (like runBlockingTest)

Slide 81

Slide 81 text

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

Slide 82

Slide 82 text

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

Slide 83

Slide 83 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 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()) } this: TestScope

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()) } UserRepo()

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() reg("Alice")

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") reg("Bob")

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") assert()

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

TestDispatchers

Slide 92

Slide 92 text

TestDispatchers StandardTestDispatcher Queues up new coroutines Use by default

Slide 93

Slide 93 text

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

Slide 94

Slide 94 text

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

Slide 95

Slide 95 text

Injecting dispatchers Something something heat exchangers

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 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 99

Slide 99 text

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

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) } 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

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.populate() fun initialize() { scope.launch { database.populate() } }

Slide 103

Slide 103 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 104

Slide 104 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 105

Slide 105 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 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

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 108

Slide 108 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 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) } Repo(...) db.populate() fun initialize() { scope.launch { database.populate() } }

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) } db.populate() Repo(...)

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() db.read() suspend fun fetchData() = withContext(ioDispatcher) { database.read() }

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() assert()

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) } fun initialize() { scope.launch { database.populate() } } This is a bad API, don’t do this

Slide 121

Slide 121 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 122

Slide 122 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 123

Slide 123 text

Keeping track of coroutines Wouldn’t want to lose a Job

Slide 124

Slide 124 text

Keeping track of coroutines ● runTest will wait for coroutines to complete if they are either:

Slide 125

Slide 125 text

Keeping track of coroutines ● runTest will wait for coroutines to complete if they are either: ● Children of the test coroutine (up to a timeout)

Slide 126

Slide 126 text

Keeping track of coroutines ● runTest will wait for coroutines to complete if they are either: ● Children of the test coroutine (up to a timeout) ● Running on the test scheduler

Slide 127

Slide 127 text

Keeping track of coroutines @Test fun uncompletedJobs() = runTest { launch(Dispatchers.IO) { delay(500L) // Do some work... } }

Slide 128

Slide 128 text

Keeping track of coroutines @Test fun uncompletedJobs() = runTest(dispatchTimeoutMs = 1000L) { launch(Dispatchers.IO) { delay(500L) // Do some work... } }

Slide 129

Slide 129 text

Keeping track of coroutines class SocketService(private val ioDispatcher: CoroutineDispatcher) { private val scope = CoroutineScope(ioDispatcher) fun shutdown() { scope.launch { // Do some async cleanup } } }

Slide 130

Slide 130 text

Keeping track of coroutines @Test fun cleanupTest() = runTest { val testDispatcher = StandardTestDispatcher(testScheduler) val service = SocketService(testDispatcher) // Do some testing... service.shutdown() } fun shutdown() { scope.launch { // Do some async cleanup } }

Slide 131

Slide 131 text

Keeping track of coroutines @Test fun cleanupTest() = runTest { val testDispatcher = StandardTestDispatcher(testScheduler) val service = SocketService(testDispatcher) // Do some testing... service.shutdown() } this: TestScope fun shutdown() { scope.launch { // Do some async cleanup } }

Slide 132

Slide 132 text

Handling the Main dispatcher A UI thread without a UI

Slide 133

Slide 133 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 134

Slide 134 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 135

Slide 135 text

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

Slide 136

Slide 136 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 {

Slide 137

Slide 137 text

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 138

Slide 138 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 139

Slide 139 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 140

Slide 140 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 141

Slide 141 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 142

Slide 142 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 143

Slide 143 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) } } If you replace the Main dispatcher with a TestDispatcher, all new TestDispatchers will automatically share its scheduler

Slide 144

Slide 144 text

Managing test objects Creating dispatchers and schedulers and scopes

Slide 145

Slide 145 text

Using TestDispatchers in the test class Repository(private val ioDispatcher: CoroutineDispatcher) { /* ... */ }

Slide 146

Slide 146 text

Using TestDispatchers in the test class Repository(private val ioDispatcher: CoroutineDispatcher) { /* ... */ } class DispatcherTypesTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() }

Slide 147

Slide 147 text

Using TestDispatchers in the test class Repository(private val ioDispatcher: CoroutineDispatcher) { /* ... */ } class DispatcherTypesTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun injectingTestDispatchers() = runTest { // Shares Main’s scheduler } }

Slide 148

Slide 148 text

Using TestDispatchers in the test class Repository(private val ioDispatcher: CoroutineDispatcher) { /* ... */ } class DispatcherTypesTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun injectingTestDispatchers() = runTest { val unconfinedRepo = Repository(mainDispatcherRule.testDispatcher) } }

Slide 149

Slide 149 text

Using TestDispatchers in the test class Repository(private val ioDispatcher: CoroutineDispatcher) { /* ... */ } class DispatcherTypesTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun injectingTestDispatchers() = runTest { val unconfinedRepo = Repository(mainDispatcherRule.testDispatcher) val standardRepo = Repository(StandardTestDispatcher()) } // ^ Shares Main’s scheduler }

Slide 150

Slide 150 text

Using TestDispatchers in the test class Repository(private val ioDispatcher: CoroutineDispatcher) { /* ... */ } class DispatcherTypesTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun injectingTestDispatchers() = runTest { val unconfinedRepo = Repository(UnconfinedTestDispatcher()) val standardRepo = Repository(StandardTestDispatcher()) } }

Slide 151

Slide 151 text

Using TestDispatchers outside the test

Slide 152

Slide 152 text

Using TestDispatchers outside the test class RepositoryTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() private val repository = Repository(???) @Test fun someRepositoryTest() = runTest { // Test the repository... } }

Slide 153

Slide 153 text

Using TestDispatchers outside the test class RepositoryTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() private val repository = Repository(UnconfinedTestDispatcher()) @Test fun someRepositoryTest() = runTest { // Test the repository... } }

Slide 154

Slide 154 text

Using TestDispatchers outside the test class RepositoryTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() private val repository = Repository(UnconfinedTestDispatcher()) } @Test fun someRepositoryTest() = runTest { // Test the repository... }

Slide 155

Slide 155 text

Using TestDispatchers outside the test class RepositoryTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() private val repository = Repository( ) } @Test fun someRepositoryTest() = runTest { // Test the repository... } mainDispatcherRule.testDispatcher

Slide 156

Slide 156 text

Using TestDispatchers outside the test class RepositoryTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() private val repository = Repository( StandardTestDispatcher( .scheduler) ) } @Test fun someRepositoryTest() = runTest { // Test the repository... } mainDispatcherRule.testDispatcher

Slide 157

Slide 157 text

Creating test objects class ExampleTest { runTest { // ... } } @Test fun someTest() =

Slide 158

Slide 158 text

Creating test objects class ExampleTest { ) testScope.runTest { // ... } } @Test fun someTest() = val testScope = TestScope(

Slide 159

Slide 159 text

Creating test objects class ExampleTest { ) testDispatcher) testScope.runTest { // ... } } @Test fun someTest() = val testScope = TestScope( val testDispatcher = StandardTestDispatcher(

Slide 160

Slide 160 text

Creating test objects class ExampleTest { val testScheduler = TestCoroutineScheduler() testScheduler) testDispatcher) testScope.runTest { // ... } } @Test fun someTest() = val testScope = TestScope( val testDispatcher = StandardTestDispatcher(

Slide 161

Slide 161 text

Flows Suspenseful streams

Slide 162

Slide 162 text

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

Slide 163

Slide 163 text

Flows

Slide 164

Slide 164 text

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

Slide 165

Slide 165 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 166

Slide 166 text

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

Slide 167

Slide 167 text

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

Slide 168

Slide 168 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 169

Slide 169 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 170

Slide 170 text

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

Slide 171

Slide 171 text

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

Slide 172

Slide 172 text

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

Slide 173

Slide 173 text

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

Slide 174

Slide 174 text

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

Slide 175

Slide 175 text

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

Slide 176

Slide 176 text

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

Slide 177

Slide 177 text

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

Slide 178

Slide 178 text

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

Slide 179

Slide 179 text

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

Slide 180

Slide 180 text

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

Slide 181

Slide 181 text

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

Slide 182

Slide 182 text

Flows @Test fun continuouslyCollect() = runTest { val dataSource = HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf() 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()

Slide 183

Slide 183 text

Flows with Turbine

Slide 184

Slide 184 text

Flows with Turbine @Test fun usingTurbine() = runTest { val dataSource = HotFakeDataSource() val repository = Repository(dataSource) }

Slide 185

Slide 185 text

Flows with Turbine @Test fun usingTurbine() = runTest { val dataSource = HotFakeDataSource() val repository = Repository(dataSource) repository.scores().test { } }

Slide 186

Slide 186 text

Flows with Turbine @Test fun usingTurbine() = runTest { val dataSource = HotFakeDataSource() val repository = Repository(dataSource) repository.scores().test { dataSource.emit(1) assertEquals(10, awaitItem()) } }

Slide 187

Slide 187 text

Flows with Turbine @Test fun usingTurbine() = runTest { val dataSource = HotFakeDataSource() val repository = Repository(dataSource) repository.scores().test { dataSource.emit(1) assertEquals(10, awaitItem()) dataSource.emit(2) awaitItem() dataSource.emit(3) assertEquals(30, awaitItem()) } }

Slide 188

Slide 188 text

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

Slide 189

Slide 189 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 190

Slide 190 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 191

Slide 191 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 192

Slide 192 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 193

Slide 193 text

StateFlows

Slide 194

Slide 194 text

StateFlows class ColdFakeRepository : MyRepository { override fun scores() = flow { emit(1) delay(100) emit(2) delay(100) emit(3) } }

Slide 195

Slide 195 text

StateFlows @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun testStateFlow() = runTest { val viewModel = MyViewModel(ColdFakeRepository()) }

Slide 196

Slide 196 text

StateFlows @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun testStateFlow() = runTest { val viewModel = MyViewModel(ColdFakeRepository()) viewModel.initialize() } fun initialize() { viewModelScope.launch { myRepository.scores().collect { score -> _data.value = score } } }

Slide 197

Slide 197 text

StateFlows @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun testStateFlow() = runTest { val viewModel = MyViewModel(ColdFakeRepository()) viewModel.initialize() assertEquals(1, viewModel.data.value) }

Slide 198

Slide 198 text

StateFlows @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun testStateFlow() = runTest { val viewModel = MyViewModel(ColdFakeRepository()) viewModel.initialize() assertEquals(1, viewModel.data.value) advanceTimeBy(101) assertEquals(2, viewModel.data.value) }

Slide 199

Slide 199 text

StateFlows @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun testStateFlow() = runTest { val viewModel = MyViewModel(ColdFakeRepository()) viewModel.initialize() assertEquals(1, viewModel.data.value) advanceTimeBy(101) assertEquals(2, viewModel.data.value) advanceTimeBy(101) assertEquals(3, viewModel.data.value) }

Slide 200

Slide 200 text

StateFlows @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun testStateFlow() = runTest { val viewModel = MyViewModel(ColdFakeRepository()) viewModel.initialize() assertEquals(1, viewModel.data.value) advanceTimeBy(101) assertEquals(2, viewModel.data.value) advanceTimeBy(101) assertEquals(3, viewModel.data.value) }

Slide 201

Slide 201 text

Summary What did we learn today?

Slide 202

Slide 202 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 203

Slide 203 text

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

Slide 204

Slide 204 text

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