Share
Embed
Untangling Coroutine Testing (Android Makers 2022)
Coroutines are embraced on Android as a tool to perform asynchronous operations and manage threading in your apps. Testing them requires some extra work and a solid understanding of scopes and dispatchers. In this talk, we’ll look at how to test coroutines with the latest available testing APIs introduced in kotlinx.coroutines 1.6, from the simplest cases all the way to Flows.
Márton Braun
April 25, 2022
Annual Pro sale · Save $30
Have presentations of your own?
Share with private links, password protection, and more control over your work.
Transcript
204 slides
-
Agenda • Testing suspending functions • The coroutine test APIs
• Best practices • Handling the Main dispatcher • Flows & StateFlows -
kotlinx.coroutines.test 1.6+ APIs runTest TestDispatcher TestScope TestCoroutineScheduler Pre-1.6 APIs runBlockingTest
TestCoroutineDispatcher TestCoroutineScope pauseDispatcher resumeDispatcher -
kotlinx.coroutines.test 1.6+ APIs runTest TestDispatcher TestScope TestCoroutineScheduler Pre-1.6 APIs runBlockingTest
TestCoroutineDispatcher TestCoroutineScope pauseDispatcher resumeDispatcher @Experimental -
kotlinx.coroutines.test 1.6+ APIs runTest TestDispatcher TestScope TestCoroutineScheduler Pre-1.6 APIs runBlockingTest
TestCoroutineDispatcher TestCoroutineScope pauseDispatcher resumeDispatcher @Experimental @Deprecated -
kotlinx.coroutines.test 1.6+ APIs runTest TestDispatcher TestScope TestCoroutineScheduler Pre-1.6 APIs runBlockingTest
TestCoroutineDispatcher TestCoroutineScope pauseDispatcher resumeDispatcher @Experimental @Deprecated @Experimental -
Testing suspending functions suspend fun fetchData(): String { delay(1000L) return
"Hello world" } @Test fun dataIsHelloWorld() { val data = fetchData() assertEquals("Hello world", data) } -
Testing suspending functions suspend fun fetchData(): String { delay(1000L) return
"Hello world" } @Test fun dataIsHelloWorld() { val data = fetchData() assertEquals("Hello world", data) } -
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 -
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 -
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 -
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 -
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 -
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 -
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 * -
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 -
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() -
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() -
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() -
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() -
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() -
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() -
Testing new coroutines @Test fun directExample() = runTest { val
repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals( listOf("Alice", "Bob"), repo.getAllUsers() ) } -
Testing new coroutines @Test fun directExample() = runTest { val
repo = UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals( listOf("Alice", "Bob"), repo.getAllUsers() ) } -
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() ) } -
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() ) } -
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() ) } -
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() ) } -
Test APIs runTest TestDispatcher TestCoroutineScheduler TestScope TestDispatcher TestDispatcher All TestDispatchers
must share the same scheduler -
• Queues up coroutines on the scheduler • You need
to advance those coroutines manually StandardTestDispatcher -
• Queues up coroutines on the scheduler • You need
to advance those coroutines manually • runTest uses a StandardTestDispatcher by default StandardTestDispatcher runTest StandardTestDispatcher TestScope -
StandardTestDispatcher @Test fun standardTest() = runTest { val repo =
UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } -
StandardTestDispatcher @Test fun standardTest() = runTest { val repo =
UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } this: TestScope -
StandardTestDispatcher @Test fun standardTest() = runTest { val repo =
UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } -
StandardTestDispatcher @Test fun standardTest() = runTest { val repo =
UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } UserRepo() -
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") -
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") -
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") -
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") -
• You need to advance those coroutines manually StandardTestDispatcher 80
ms 90 ms 100 ms 500 ms 750 ms -
• You need to advance those coroutines manually StandardTestDispatcher 80
ms 90 ms 100 ms 500 ms 750 ms • runCurrent() -
• You need to advance those coroutines manually StandardTestDispatcher •
runCurrent() 80 ms 90 ms 100 ms 500 ms 750 ms -
• You need to advance those coroutines manually StandardTestDispatcher •
runCurrent() • advanceTimeBy(delayTimeMillis: Long) 80 ms 90 ms 100 ms 500 ms 750 ms -
• You need to advance those coroutines manually StandardTestDispatcher •
runCurrent() • advanceTimeBy(delayTimeMillis: Long) 80 ms 90 ms 100 ms 500 ms 750 ms -
• You need to advance those coroutines manually StandardTestDispatcher •
runCurrent() • advanceTimeBy(delayTimeMillis: Long) 80 ms 90 ms 100 ms 500 ms 750 ms -
• You need to advance those coroutines manually StandardTestDispatcher •
runCurrent() • advanceTimeBy(delayTimeMillis: Long) • advanceUntilIdle() 80 ms 90 ms 100 ms 500 ms 750 ms -
• You need to advance those coroutines manually StandardTestDispatcher •
runCurrent() • advanceTimeBy(delayTimeMillis: Long) • advanceUntilIdle() 80 ms 90 ms 100 ms 500 ms 750 ms -
StandardTestDispatcher @Test fun standardTest() = runTest { val repo =
UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } -
StandardTestDispatcher @Test fun standardTest() = runTest { val repo =
UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } advanceUntilIdle() assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } -
StandardTestDispatcher @Test fun standardTest() = runTest { val repo =
UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } advanceUntilIdle() assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } -
StandardTestDispatcher @Test fun standardTest() = runTest { val repo =
UserRepository() launch { repo.register("Alice") } launch { repo.register("Bob") } advanceUntilIdle() assertEquals(listOf("Alice", "Bob"), repo.getAllUsers()) } UserRepo() -
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") -
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") -
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") -
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") -
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") -
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() -
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() -
UnconfinedTestDispatcher • Starts new coroutines eagerly (like runBlockingTest) • Can
be a good choice for simple tests -
UnconfinedTestDispatcher • Starts new coroutines eagerly (like runBlockingTest) • Can
be a good choice for simple tests • Does not emulate real concurrency -
UnconfinedTestDispatcher @Test fun unconfinedTest() = runTest(UnconfinedTestDispatcher()) { val userRepo =
UserRepository() launch { userRepo.register("Alice") } launch { userRepo.register("Bob") } assertEquals(listOf("Alice", "Bob"), userRepo.getAllUsers()) } -
UnconfinedTestDispatcher @Test fun unconfinedTest() = runTest(UnconfinedTestDispatcher()) { val userRepo =
UserRepository() launch { userRepo.register("Alice") } launch { userRepo.register("Bob") } assertEquals(listOf("Alice", "Bob"), userRepo.getAllUsers()) } -
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 -
UnconfinedTestDispatcher @Test fun unconfinedTest() = runTest(UnconfinedTestDispatcher()) { val userRepo =
UserRepository() launch { userRepo.register("Alice") } launch { userRepo.register("Bob") } assertEquals(listOf("Alice", "Bob"), userRepo.getAllUsers()) } UserRepo() -
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") -
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") -
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() -
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() -
TestDispatchers StandardTestDispatcher Queues up new coroutines Use by default UnconfinedTestDispatcher
Starts new coroutines eagerly Use selectively -
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 -
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() } } -
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() } } -
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() } } -
Injecting dispatchers @Test fun repoTest() = runTest { val repository
= Repository(FakeDatabase()) repository.initialize() val data = repository.fetchData() assertEquals("Hello world", data) } -
Injecting dispatchers @Test fun repoTest() = runTest { val repository
= Repository(FakeDatabase()) repository.initialize() val data = repository.fetchData() assertEquals("Hello world", data) } Test thread Dispatchers.IO -
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 -
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() } } -
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() } -
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() -
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) } -
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) } -
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) } -
, 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 -
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 , -
FakeDatabase(), @Test fun repoTest() = runTest { val repository =
Repository( ) repository.initialize() val data = repository.fetchData() assertEquals("Hello world", data) } Injecting dispatchers -
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() -
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 -
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) } -
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(...) -
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() } } -
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(...) -
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() -
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() } -
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() -
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 -
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<Unit> { return scope.async { } } database.populate() -
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() -
Keeping track of coroutines • runTest will wait for coroutines
to complete if they are either: -
Keeping track of coroutines • runTest will wait for coroutines
to complete if they are either: • Children of the test coroutine (up to a timeout) -
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 -
Keeping track of coroutines @Test fun uncompletedJobs() = runTest {
launch(Dispatchers.IO) { delay(500L) // Do some work... } } -
Keeping track of coroutines @Test fun uncompletedJobs() = runTest(dispatchTimeoutMs =
1000L) { launch(Dispatchers.IO) { delay(500L) // Do some work... } } -
Keeping track of coroutines class SocketService(private val ioDispatcher: CoroutineDispatcher) {
private val scope = CoroutineScope(ioDispatcher) fun shutdown() { scope.launch { // Do some async cleanup } } } -
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 } } -
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 } } -
Handling the Main dispatcher class HomeViewModel : ViewModel() { private
val _message = MutableStateFlow("") val message: StateFlow<String> get() = _message fun loadMessage() { viewModelScope.launch { _message.value = "Greetings!" } } } -
Handling the Main dispatcher class HomeViewModel : ViewModel() { private
val _message = MutableStateFlow("") val message: StateFlow<String> get() = _message fun loadMessage() { viewModelScope.launch { _message.value = "Greetings!" } } } -
Handling the Main dispatcher } val viewModel = HomeViewModel() viewModel.loadMessage()
assertEquals("Greetings!", viewModel.message.value) @Test fun testGreeting() = runTest { -
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 { -
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 { -
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() } } -
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!" } } -
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() -
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() -
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) } } -
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 -
Using TestDispatchers in the test class Repository(private val ioDispatcher: CoroutineDispatcher)
{ /* ... */ } class DispatcherTypesTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() } -
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 } } -
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) } } -
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 } -
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()) } } -
Using TestDispatchers outside the test class RepositoryTest { @get:Rule val
mainDispatcherRule = MainDispatcherRule() private val repository = Repository(???) @Test fun someRepositoryTest() = runTest { // Test the repository... } } -
Using TestDispatchers outside the test class RepositoryTest { @get:Rule val
mainDispatcherRule = MainDispatcherRule() private val repository = Repository(UnconfinedTestDispatcher()) @Test fun someRepositoryTest() = runTest { // Test the repository... } } -
Using TestDispatchers outside the test class RepositoryTest { @get:Rule val
mainDispatcherRule = MainDispatcherRule() private val repository = Repository(UnconfinedTestDispatcher()) } @Test fun someRepositoryTest() = runTest { // Test the repository... } -
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 -
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 -
Creating test objects class ExampleTest { runTest { // ...
} } @Test fun someTest() = -
Creating test objects class ExampleTest { ) testScope.runTest { //
... } } @Test fun someTest() = val testScope = TestScope( -
Creating test objects class ExampleTest { ) testDispatcher) testScope.runTest {
// ... } } @Test fun someTest() = val testScope = TestScope( val testDispatcher = StandardTestDispatcher( -
Creating test objects class ExampleTest { val testScheduler = TestCoroutineScheduler()
testScheduler) testDispatcher) testScope.runTest { // ... } } @Test fun someTest() = val testScope = TestScope( val testDispatcher = StandardTestDispatcher( -
Flows interface DataSource { fun counts(): Flow<Int> } class Repository(private
val dataSource: DataSource) { fun scores(): Flow<Int> { return dataSource.counts().map { it * 10 } } } -
Flows interface DataSource { fun counts(): Flow<Int> } class Repository(private
val dataSource: DataSource) { fun scores(): Flow<Int> { return dataSource.counts().map { it * 10 } } } -
Flows interface DataSource { fun counts(): Flow<Int> } class Repository(private
val dataSource: DataSource) { fun scores(): Flow<Int> { return dataSource.counts().map { it * 10 } } } class ColdFakeDataSource : DataSource { override fun counts(): Flow<Int> { return flowOf(1, 2, 3, 4) } } -
Flows @Test fun useTerminalOperators() = runTest { val repository =
Repository(ColdFakeDataSource()) } -
Flows @Test fun useTerminalOperators() = runTest { val repository =
Repository(ColdFakeDataSource()) val first = repository.scores().first() assertEquals(10, first) } -
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) } -
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]) } -
Flows class HotFakeDataSource : DataSource { private val flow =
MutableSharedFlow<Int>() suspend fun emit(value: Int) = flow.emit(value) override fun counts(): Flow<Int> = flow } -
Flows class HotFakeDataSource : DataSource { private val flow =
MutableSharedFlow<Int>() suspend fun emit(value: Int) = flow.emit(value) override fun counts(): Flow<Int> = flow } -
Flows class HotFakeDataSource : DataSource { private val flow =
MutableSharedFlow<Int>() suspend fun emit(value: Int) = flow.emit(value) override fun counts(): Flow<Int> = flow } -
Flows class HotFakeDataSource : DataSource { private val flow =
MutableSharedFlow<Int>() suspend fun emit(value: Int) = flow.emit(value) override fun counts(): Flow<Int> = flow } -
Flows @Test fun continuouslyCollect() = runTest { val dataSource =
HotFakeDataSource() val repository = Repository(dataSource) } -
Flows @Test fun continuouslyCollect() = runTest { val dataSource =
HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf<Int>() } -
Flows @Test fun continuouslyCollect() = runTest { val dataSource =
HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf<Int>() val collectJob = launch(UnconfinedTestDispatcher()) { repository.scores().collect { values += it } } } -
Flows @Test fun continuouslyCollect() = runTest { val dataSource =
HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf<Int>() val collectJob = launch(UnconfinedTestDispatcher()) { repository.scores().collect { values += it } } } -
Flows @Test fun continuouslyCollect() = runTest { val dataSource =
HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf<Int>() val collectJob = launch(UnconfinedTestDispatcher()) { repository.scores().collect { values += it } } } -
Flows @Test fun continuouslyCollect() = runTest { val dataSource =
HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf<Int>() val collectJob = launch(UnconfinedTestDispatcher()) { repository.scores().toList(values) } } -
Flows @Test fun continuouslyCollect() = runTest { val dataSource =
HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf<Int>() val collectJob = launch(UnconfinedTestDispatcher()) { repository.scores().toList(values) } dataSource.emit(1) assertEquals(10, values[0]) } -
Flows @Test fun continuouslyCollect() = runTest { val dataSource =
HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf<Int>() val collectJob = launch(UnconfinedTestDispatcher()) { repository.scores().toList(values) } dataSource.emit(1) assertEquals(10, values[0]) } collectJob.cancel() -
Flows @Test fun continuouslyCollect() = runTest { val dataSource =
HotFakeDataSource() val repository = Repository(dataSource) val values = mutableListOf<Int>() 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() -
Flows with Turbine @Test fun usingTurbine() = runTest { val
dataSource = HotFakeDataSource() val repository = Repository(dataSource) } -
Flows with Turbine @Test fun usingTurbine() = runTest { val
dataSource = HotFakeDataSource() val repository = Repository(dataSource) repository.scores().test { } } -
Flows with Turbine @Test fun usingTurbine() = runTest { val
dataSource = HotFakeDataSource() val repository = Repository(dataSource) repository.scores().test { dataSource.emit(1) assertEquals(10, awaitItem()) } } -
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()) } } -
interface MyRepository { fun scores(): Flow<Int> } class MyViewModel(private val
myRepository: MyRepository) : ViewModel() { private val _data = MutableStateFlow(0) val data: StateFlow<Int> = _data.asStateFlow() fun initialize() { viewModelScope.launch { myRepository.scores().collect { score -> _data.value = score } } } } StateFlows -
interface MyRepository { fun scores(): Flow<Int> } class MyViewModel(private val
myRepository: MyRepository) : ViewModel() { private val _data = MutableStateFlow(0) val data: StateFlow<Int> = _data.asStateFlow() fun initialize() { viewModelScope.launch { myRepository.scores().collect { score -> _data.value = score } } } } StateFlows -
interface MyRepository { fun scores(): Flow<Int> } class MyViewModel(private val
myRepository: MyRepository) : ViewModel() { private val _data = MutableStateFlow(0) val data: StateFlow<Int> = _data.asStateFlow() fun initialize() { viewModelScope.launch { myRepository.scores().collect { score -> _data.value = score } } } } StateFlows -
interface MyRepository { fun scores(): Flow<Int> } class MyViewModel(private val
myRepository: MyRepository) : ViewModel() { private val _data = MutableStateFlow(0) val data: StateFlow<Int> = _data.asStateFlow() fun initialize() { viewModelScope.launch { myRepository.scores().collect { score -> _data.value = score } } } } StateFlows -
StateFlows class ColdFakeRepository : MyRepository { override fun scores() =
flow { emit(1) delay(100) emit(2) delay(100) emit(3) } } -
StateFlows @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun testStateFlow() =
runTest { val viewModel = MyViewModel(ColdFakeRepository()) } -
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 } } } -
StateFlows @get:Rule val mainDispatcherRule = MainDispatcherRule() @Test fun testStateFlow() =
runTest { val viewModel = MyViewModel(ColdFakeRepository()) viewModel.initialize() assertEquals(1, viewModel.data.value) } -
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) } -
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) } -
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) } -
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!)