【发布时间】:2020-05-11 13:13:44
【问题描述】:
使用这个manual 来测试协程。编写一个预期会引发异常崩溃而不是通过测试的测试。我想知道我做错了什么。
private val testDispatcher = TestCoroutineDispatcher()
@Before
fun setup() {
// provide the scope explicitly, in this example using a constructor parameter
Dispatchers.setMain(testDispatcher)
}
@After
fun cleanUp() {
Dispatchers.resetMain()
testDispatcher.cleanupTestCoroutines()
}
@Test(expected = RuntimeException::class)
fun testSomeFunctionWithException() = testDispatcher.runBlockingTest {
someFunctionWithException()
}
private fun someFunctionWithException() {
MainScope().launch {
throw RuntimeException("Failed via TEST exception")
}
}
上面和下面的测试方法
private val testScope = TestCoroutineScope()
private lateinit var subject: Subject
@Before
fun setup() {
// provide the scope explicitly, in this example using a constructor parameter
subject = Subject(testScope)
}
@After
fun cleanUp() {
testScope.cleanupTestCoroutines()
}
@Test(expected = RuntimeException::class)
fun testFooWithException() = testScope.runBlockingTest {
subject.fooWithException()
}
class Subject(private val scope: CoroutineScope) {
fun fooWithException() {
scope.launch {
println("fooWithException() thread: ${Thread.currentThread().name}")
throw RuntimeException("Failed via TEST exception")
}
}
}
即使它们都崩溃了
注意:最好在不复杂的情况下提供 TestCoroutineScope 代码,因为它还会将异常提升为测试失败。
- 为什么它们都崩溃了?
- 为什么有作用域的那个不失败反而崩溃了?
【问题讨论】:
标签: unit-testing kotlin kotlin-coroutines