如何在测试规则中使JUnit测试失败

Zak*_*rdi 5 junit junit4 kotlin

我有一些异步代码,可能会引发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) }
    }
}
Run Code Online (Sandbox Code Playgroud)