我有一些异步代码,可能会引发JUnit错过的异常(因此测试通过)。
我创建了一个TestRule
来将这些异常收集到一个列表中。任何测试完成后,断言将遍历列表,并且如果异常列表为非空,则测试将失败。
我不想在测试完成后失败,而是希望在发生异常时立即失败。可以使用TestRule
来做到这一点吗?
我的TestRule
/**
* Coroutines can throw exceptions that can go unnoticed by the JUnit Test Runner which will pass
* a test that should have failed. This rule will ensure the test fails, provided that you use the
* [CoroutineContext] provided by [dispatcher].
*/
class CoroutineExceptionRule : TestWatcher(), TestRule {
private val exceptions = Collections.synchronizedList(mutableListOf<Throwable>())
val dispatcher: CoroutineContext
get() = Unconfined + CoroutineExceptionHandler { _, throwable ->
// I want to hook into test lifecycle and fail test immediately here
exceptions.add(throwable)
// this throw will not always fail the test. this does print the stacktrace at least
throw throwable
}
override fun starting(description: Description) {
exceptions.clear()
}
override fun finished(description: Description) {
// instead of waiting for test to finish to fail it
exceptions.forEach { throw AssertionError(it) }
}
}