使用这个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
代码,因为它还会提升测试失败的异常。
- 为什么两人都崩溃了?
- 为什么有范围的不会失败而不是崩溃?
TestCoroutineScope
uses TestCoroutineExceptionHandler
它将处理协程中抛出的所有异常,并将它们收集在uncaughtExceptions
列表,尽管第一个列表将在期间被重新抛出cleanUp
或者更具体地说,当cleanupTestCoroutines()
被调用,因此您必须对该异常采取一些措施以防止测试失败。
@After
fun cleanUp() {
try {
testScope.cleanupTestCoroutines()
} catch (e: Exception) {
//Do something here
}
}
在测试过程中您可以检查uncaughtExceptions
列出以便做出你的断言:
@Test(expected = RuntimeException::class)
fun testFooWithException() = testScope.runBlockingTest {
subject.fooWithException()
assertEquals(1, uncaughtExceptions.size)
assertEquals(uncaughtExceptions[0].message, "Failed via TEST exception")
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)