1 /* 2 * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 */ 4 5 package kotlinx.coroutines.android 6 7 import android.os.* 8 import kotlinx.coroutines.* 9 import org.junit.* 10 import org.junit.runner.* 11 import org.robolectric.* 12 import org.robolectric.annotation.* 13 14 @RunWith(RobolectricTestRunner::class) 15 @Config(manifest = Config.NONE, sdk = [28]) 16 @LooperMode(LooperMode.Mode.LEGACY) 17 class DisabledHandlerTest : TestBase() { 18 19 private var delegateToSuper = false 20 private val disabledDispatcher = object : Handler() { sendMessageAtTimenull21 override fun sendMessageAtTime(msg: Message?, uptimeMillis: Long): Boolean { 22 if (delegateToSuper) return super.sendMessageAtTime(msg, uptimeMillis) 23 return false 24 } 25 }.asCoroutineDispatcher() 26 27 @Test testRunBlockingnull28 fun testRunBlocking() { 29 expect(1) 30 try { 31 runBlocking(disabledDispatcher) { 32 expectUnreached() 33 } 34 expectUnreached() 35 } catch (e: CancellationException) { 36 finish(2) 37 } 38 } 39 40 @Test testInvokeOnCancellationnull41 fun testInvokeOnCancellation() = runTest { 42 val job = launch(disabledDispatcher, start = CoroutineStart.LAZY) { expectUnreached() } 43 job.invokeOnCompletion { if (it != null) expect(2) } 44 yield() 45 expect(1) 46 job.join() 47 finish(3) 48 } 49 50 @Test <lambda>null51 fun testWithTimeout() = runTest { 52 delegateToSuper = true 53 try { 54 withContext(disabledDispatcher) { 55 expect(1) 56 delegateToSuper = false 57 delay(Long.MAX_VALUE - 1) 58 expectUnreached() 59 } 60 expectUnreached() 61 } catch (e: CancellationException) { 62 finish(2) 63 } 64 } 65 } 66