|
5 | 5 | package kotlinx.coroutines.test
|
6 | 6 |
|
7 | 7 | import kotlinx.coroutines.*
|
| 8 | +import kotlin.coroutines.* |
8 | 9 | import kotlin.test.*
|
9 | 10 |
|
10 | 11 | class TestCoroutineScopeTest {
|
| 12 | + /** Tests failing to create a [TestCoroutineScope] with incorrect contexts. */ |
11 | 13 | @Test
|
12 |
| - fun whenGivenInvalidExceptionHandler_throwsException() { |
13 |
| - val handler = CoroutineExceptionHandler { _, _ -> } |
14 |
| - assertFails { |
15 |
| - TestCoroutineScope(handler) |
| 14 | + fun testCreateThrowsOnInvalidArguments() { |
| 15 | + for (ctx in invalidContexts) { |
| 16 | + assertFailsWith<IllegalArgumentException> { |
| 17 | + TestCoroutineScope(ctx) |
| 18 | + } |
16 | 19 | }
|
17 | 20 | }
|
18 | 21 |
|
| 22 | + /** Tests that a newly-created [TestCoroutineScope] provides the correct scheduler. */ |
19 | 23 | @Test
|
20 |
| - fun whenGivenInvalidDispatcher_throwsException() { |
21 |
| - assertFails { |
22 |
| - TestCoroutineScope(Dispatchers.Default) |
| 24 | + fun testCreateProvidesScheduler() { |
| 25 | + // Creates a new scheduler. |
| 26 | + run { |
| 27 | + val scope = TestCoroutineScope() |
| 28 | + assertNotNull(scope.coroutineContext[TestCoroutineScheduler]) |
| 29 | + } |
| 30 | + // Reuses the scheduler that the dispatcher is linked to. |
| 31 | + run { |
| 32 | + val dispatcher = TestCoroutineDispatcher() |
| 33 | + val scope = TestCoroutineScope(dispatcher) |
| 34 | + assertSame(dispatcher.scheduler, scope.coroutineContext[TestCoroutineScheduler]) |
| 35 | + } |
| 36 | + // Uses the scheduler passed to it. |
| 37 | + run { |
| 38 | + val scheduler = TestCoroutineScheduler() |
| 39 | + val scope = TestCoroutineScope(scheduler) |
| 40 | + assertSame(scheduler, scope.coroutineContext[TestCoroutineScheduler]) |
| 41 | + assertSame(scheduler, (scope.coroutineContext[ContinuationInterceptor] as TestDispatcher).scheduler) |
| 42 | + } |
| 43 | + // Doesn't touch the passed dispatcher and the scheduler if they match. |
| 44 | + run { |
| 45 | + val scheduler = TestCoroutineScheduler() |
| 46 | + val dispatcher = TestCoroutineDispatcher(scheduler) |
| 47 | + val scope = TestCoroutineScope(scheduler + dispatcher) |
| 48 | + assertSame(scheduler, scope.coroutineContext[TestCoroutineScheduler]) |
| 49 | + assertSame(dispatcher, scope.coroutineContext[ContinuationInterceptor]) |
23 | 50 | }
|
24 | 51 | }
|
| 52 | + |
| 53 | + private val invalidContexts = listOf( |
| 54 | + Dispatchers.Default, // not a [TestDispatcher] |
| 55 | + TestCoroutineDispatcher() + TestCoroutineScheduler(), // the dispatcher is not linked to the scheduler |
| 56 | + CoroutineExceptionHandler { _, _ -> }, // not an `UncaughtExceptionCaptor` |
| 57 | + ) |
25 | 58 | }
|
0 commit comments