1 package com.android.compose.test 2 3 import androidx.compose.ui.test.ExperimentalTestApi 4 import androidx.compose.ui.test.TestMonotonicFrameClock 5 import kotlinx.coroutines.CoroutineScope 6 import kotlinx.coroutines.ExperimentalCoroutinesApi 7 import kotlinx.coroutines.test.TestCoroutineScheduler 8 import kotlinx.coroutines.test.TestScope 9 import kotlinx.coroutines.test.runTest 10 import kotlinx.coroutines.withContext 11 12 /** 13 * This method creates a [CoroutineScope] that can be used in animations created in a composable 14 * function. 15 * 16 * The [TestCoroutineScheduler] is passed to provide the functionality to wait for idle. 17 * 18 * Note: Please refer to the documentation for [runTest], as this feature utilizes it. This will 19 * provide a comprehensive understanding of all its behaviors. 20 */ 21 @OptIn(ExperimentalTestApi::class, ExperimentalCoroutinesApi::class) <lambda>null22fun runMonotonicClockTest(block: suspend MonotonicClockTestScope.() -> Unit) = runTest { 23 val testScope: TestScope = this 24 25 withContext(TestMonotonicFrameClock(coroutineScope = testScope)) { 26 val testScopeWithMonotonicFrameClock: CoroutineScope = this 27 28 val scope = 29 MonotonicClockTestScope( 30 testScope = testScopeWithMonotonicFrameClock, 31 testScheduler = testScope.testScheduler, 32 backgroundScope = backgroundScope, 33 ) 34 35 // Run the test 36 scope.block() 37 } 38 } 39 40 /** 41 * A coroutine scope that for launching test coroutines for Compose. 42 * 43 * @param testScheduler The delay-skipping scheduler used by the test dispatchers running the code 44 * in this scope (see [TestScope.testScheduler]). 45 * @param backgroundScope A scope for background work (see [TestScope.backgroundScope]). 46 */ 47 class MonotonicClockTestScope( 48 testScope: CoroutineScope, 49 val testScheduler: TestCoroutineScheduler, 50 val backgroundScope: CoroutineScope, 51 ) : CoroutineScope by testScope 52