|
| 1 | +/* |
| 2 | + * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
| 3 | + */ |
| 4 | +package kotlinx.coroutines.test |
| 5 | + |
| 6 | +import kotlinx.coroutines.* |
| 7 | +import org.junit.* |
| 8 | +import org.junit.Test |
| 9 | +import kotlin.coroutines.* |
| 10 | +import kotlin.test.* |
| 11 | + |
| 12 | +class MainDispatcherInjectorTest : TestBase() { |
| 13 | + |
| 14 | + @Before |
| 15 | + fun setUp() { |
| 16 | + MainDispatcherInjector.reset() |
| 17 | + } |
| 18 | + |
| 19 | + @Test |
| 20 | + fun testInjection() = runTest { |
| 21 | + val mainThread = Thread.currentThread() |
| 22 | + newSingleThreadContext("testInjection").use { threadPool -> |
| 23 | + withContext(Dispatchers.Main) { |
| 24 | + assertSame(mainThread, Thread.currentThread()) |
| 25 | + } |
| 26 | + |
| 27 | + MainDispatcherInjector.inject(threadPool) |
| 28 | + withContext(Dispatchers.Main) { |
| 29 | + assertNotSame(mainThread, Thread.currentThread()) |
| 30 | + } |
| 31 | + assertSame(mainThread, Thread.currentThread()) |
| 32 | + |
| 33 | + withContext(Dispatchers.Main.immediate) { |
| 34 | + assertNotSame(mainThread, Thread.currentThread()) |
| 35 | + } |
| 36 | + assertSame(mainThread, Thread.currentThread()) |
| 37 | + |
| 38 | + MainDispatcherInjector.inject(Dispatchers.Unconfined) |
| 39 | + withContext(Dispatchers.Main.immediate) { |
| 40 | + assertSame(mainThread, Thread.currentThread()) |
| 41 | + } |
| 42 | + assertSame(mainThread, Thread.currentThread()) |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + @Test |
| 47 | + fun testImmediateDispatcher() = runTest { |
| 48 | + MainDispatcherInjector.inject(ImmediateDispatcher()) |
| 49 | + expect(1) |
| 50 | + withContext(Dispatchers.Main) { |
| 51 | + expect(3) |
| 52 | + } |
| 53 | + |
| 54 | + MainDispatcherInjector.inject(RegularDispatcher()) |
| 55 | + withContext(Dispatchers.Main) { |
| 56 | + expect(6) |
| 57 | + } |
| 58 | + |
| 59 | + finish(7) |
| 60 | + } |
| 61 | + |
| 62 | + private inner class ImmediateDispatcher : CoroutineDispatcher() { |
| 63 | + override fun isDispatchNeeded(context: CoroutineContext): Boolean { |
| 64 | + expect(2) |
| 65 | + return false |
| 66 | + } |
| 67 | + |
| 68 | + override fun dispatch(context: CoroutineContext, block: Runnable) = expectUnreached() |
| 69 | + } |
| 70 | + |
| 71 | + private inner class RegularDispatcher : CoroutineDispatcher() { |
| 72 | + override fun isDispatchNeeded(context: CoroutineContext): Boolean { |
| 73 | + expect(4) |
| 74 | + return true |
| 75 | + } |
| 76 | + |
| 77 | + override fun dispatch(context: CoroutineContext, block: Runnable) { |
| 78 | + expect(5) |
| 79 | + block.run() |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments