Slide 1

Slide 1 text

Márton Braun @zsmb13 Developer Relations Engineer Google Untangling Coroutine Testing KotlinConf’23 Amsterdam

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

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

Slide 4

Slide 4 text

Testing suspending functions runTest. run.

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

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

Slide 8

Slide 8 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 9

Slide 9 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 10

Slide 10 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 11

Slide 11 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 12

Slide 12 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 13

Slide 13 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 14

Slide 14 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 15

Slide 15 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 16

Slide 16 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 17

Slide 17 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 18

Slide 18 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 19

Slide 19 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 20

Slide 20 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 21

Slide 21 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 22

Slide 22 text

Testing new coroutines

Slide 23

Slide 23 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 24

Slide 24 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 25

Slide 25 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 26

Slide 26 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 27

Slide 27 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 28

Slide 28 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 29

Slide 29 text

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

Slide 30

Slide 30 text

Test APIs runTest

Slide 31

Slide 31 text

Test APIs runTest TestScope

Slide 32

Slide 32 text

Test APIs runTest TestDispatcher TestScope

Slide 33

Slide 33 text

Test APIs runTest TestDispatcher TestCoroutineScheduler TestScope

Slide 34

Slide 34 text

Test APIs runTest TestDispatcher TestCoroutineScheduler TestScope TestDispatcher TestDispatcher

Slide 35

Slide 35 text

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

Slide 36

Slide 36 text

Test APIs TestDispatcher TestCoroutineScheduler

Slide 37

Slide 37 text

Test APIs TestCoroutineScheduler StandardTestDispatcher UnconfinedTestDispatcher TestDispatcher

Slide 38

Slide 38 text

StandardTestDispatcher

Slide 39

Slide 39 text

● Queues up coroutines on the scheduler StandardTestDispatcher

Slide 40

Slide 40 text

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

Slide 41

Slide 41 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 42

Slide 42 text

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

Slide 43

Slide 43 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 44

Slide 44 text

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

Slide 45

Slide 45 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 46

Slide 46 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 47

Slide 47 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 48

Slide 48 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 49

Slide 49 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 50

Slide 50 text

StandardTestDispatcher ● You need to advance those coroutines manually

Slide 51

Slide 51 text

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

Slide 52

Slide 52 text

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

Slide 53

Slide 53 text

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

Slide 54

Slide 54 text

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

Slide 55

Slide 55 text

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

Slide 56

Slide 56 text

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

Slide 57

Slide 57 text

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

Slide 58

Slide 58 text

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

Slide 59

Slide 59 text

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

Slide 60

Slide 60 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 61

Slide 61 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 62

Slide 62 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 63

Slide 63 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 64

Slide 64 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 65

Slide 65 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 66

Slide 66 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 67

Slide 67 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 68

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

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

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

Slide 71

Slide 71 text

UnconfinedTestDispatcher

Slide 72

Slide 72 text

UnconfinedTestDispatcher ● Starts new coroutines eagerly

Slide 73

Slide 73 text

UnconfinedTestDispatcher ● Starts new coroutines eagerly ● Can be a good choice for simple tests

Slide 74

Slide 74 text

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

Slide 75

Slide 75 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 76

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

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

Slide 78 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 79

Slide 79 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 80

Slide 80 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 81

Slide 81 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 82

Slide 82 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 83

Slide 83 text

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

Slide 84

Slide 84 text

TestDispatchers Queues up new coroutines Use by default Starts new coroutines eagerly Use selectively • As the Main dispatcher • For coroutines that collect Flows StandardTestDispatcher UnconfinedTestDispatcher

Slide 85

Slide 85 text

Injecting dispatchers Something something heat exchangers

Slide 86

Slide 86 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 87

Slide 87 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 88

Slide 88 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 89

Slide 89 text

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

Slide 90

Slide 90 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 91

Slide 91 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 92

Slide 92 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 93

Slide 93 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 94

Slide 94 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 95

Slide 95 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 96

Slide 96 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 97

Slide 97 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 98

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

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

Slide 100 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 101

Slide 101 text

Dispatchers.IO Injecting dispatchers class Repository( private val ioDispatcher: CoroutineContext = 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 102

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

Slide 103 text

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

Slide 104

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

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

Slide 106 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 107

Slide 107 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 108

Slide 108 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 109

Slide 109 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 110

Slide 110 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 111

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

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

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

Slide 115

Slide 115 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 116

Slide 116 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 117

Slide 117 text

Handling the Main dispatcher A UI thread without a UI

Slide 118

Slide 118 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 119

Slide 119 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 120

Slide 120 text

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

Slide 121

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

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

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

Slide 124 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 this: TestScope

Slide 125

Slide 125 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 126

Slide 126 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 127

Slide 127 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 128

Slide 128 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 129

Slide 129 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 130

Slide 130 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 131

Slide 131 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 132

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

Slide 133 text

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

Slide 134

Slide 134 text

Flows Suspenseful streams

Slide 135

Slide 135 text

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

Slide 136

Slide 136 text

Flows Test Repository Fake Data Source

Slide 137

Slide 137 text

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

Slide 138

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

Slide 139 text

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

Slide 140

Slide 140 text

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

Slide 141

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

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

Slide 143 text

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

Slide 144

Slide 144 text

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

Slide 145

Slide 145 text

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

Slide 146

Slide 146 text

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

Slide 147

Slide 147 text

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

Slide 148

Slide 148 text

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

Slide 149

Slide 149 text

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

Slide 150

Slide 150 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 151

Slide 151 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 152

Slide 152 text

Flows val collectJob = 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) launch(UnconfinedTestDispatcher()) { } }

Slide 153

Slide 153 text

Flows @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) this: TestScope backgroundScope.launch(UnconfinedTestDispatcher()) { } }

Slide 154

Slide 154 text

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

Slide 155

Slide 155 text

No content

Slide 156

Slide 156 text

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

Slide 157

Slide 157 text

Stream StateFlows State holder

Slide 158

Slide 158 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 159

Slide 159 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 160

Slide 160 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 161

Slide 161 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 162

Slide 162 text

StateFlows Test ViewModel Fake Repository

Slide 163

Slide 163 text

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

Slide 164

Slide 164 text

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

Slide 165

Slide 165 text

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

Slide 166

Slide 166 text

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

Slide 167

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

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

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

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

Slide 171 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 172

Slide 172 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 173

Slide 173 text

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

Slide 174

Slide 174 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 175

Slide 175 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 176

Slide 176 text

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

Slide 177

Slide 177 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 178

Slide 178 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 179

Slide 179 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 180

Slide 180 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 181

Slide 181 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 182

Slide 182 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 183

Slide 183 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 184

Slide 184 text

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

Slide 185

Slide 185 text

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

Slide 186

Slide 186 text

Summary What did we learn today?

Slide 187

Slide 187 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!) ● Use backgroundScope to create Flow collectors

Slide 188

Slide 188 text

Resources ● goo.gle/coroutine-test-guide ● goo.gle/flow-test-guide ● github.com/cashapp/turbine

Slide 189

Slide 189 text

Thank you, and don’t forget to vote! KotlinConf’23 Amsterdam Márton Braun @zsmb13 Developer Relations Engineer Google