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