/
TestCoroutineScopeTest.kt
97 lines (87 loc) · 2.78 KB
/
TestCoroutineScopeTest.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.test
import kotlinx.coroutines.*
import kotlin.coroutines.*
import kotlin.test.*
class TestCoroutineScopeTest {
@Test
fun whenGivenInvalidExceptionHandler_throwsException() {
val handler = CoroutineExceptionHandler { _, _ -> }
assertFails {
TestCoroutineScope(handler)
}
}
@Test
fun whenGivenInvalidDispatcher_throwsException() {
assertFails {
TestCoroutineScope(Dispatchers.Default)
}
}
/** Tests that the cleanup procedure throws if there were uncompleted delays by the end. */
@Test
fun testPresentDelaysThrowing() {
val scope = TestCoroutineScope()
var result = false
scope.launch {
delay(5)
result = true
}
assertFalse(result)
assertFailsWith<AssertionError> { scope.cleanupTestCoroutines() }
assertFalse(result)
}
/** Tests that the cleanup procedure throws if there were active jobs by the end. */
@Test
fun testActiveJobsThrowing() {
val scope = TestCoroutineScope()
var result = false
val deferred = CompletableDeferred<String>()
scope.launch {
deferred.await()
result = true
}
assertFalse(result)
assertFailsWith<AssertionError> { scope.cleanupTestCoroutines() }
assertFalse(result)
}
/** Tests that the cleanup procedure doesn't throw if it detects that the job is already cancelled. */
@Test
fun testCancelledDelaysNotThrowing() {
val scope = TestCoroutineScope()
var result = false
val deferred = CompletableDeferred<String>()
val job = scope.launch {
deferred.await()
result = true
}
job.cancel()
assertFalse(result)
scope.cleanupTestCoroutines()
assertFalse(result)
}
/** Tests that the coroutine scope completes its job if the job was not passed to it as an argument. */
@Test
fun testCompletesOwnJob() {
val scope = TestCoroutineScope()
var handlerCalled = false
scope.coroutineContext.job.invokeOnCompletion {
handlerCalled = true
}
scope.cleanupTestCoroutines()
assertTrue(handlerCalled)
}
/** Tests that the coroutine scope completes its job if the job was not passed to it as an argument. */
@Test
fun testDoesNotCompleteGivenJob() {
var handlerCalled = false
val job = Job()
job.invokeOnCompletion {
handlerCalled = true
}
val scope = TestCoroutineScope(job)
scope.cleanupTestCoroutines()
assertFalse(handlerCalled)
}
}