如何从测试规则中使JUnit测试失败
我有一些异步代码,可能抛出JUnit未命中的异常(因此测试通过) 我创建了一个如何从测试规则中使JUnit测试失败,junit,kotlin,junit4,Junit,Kotlin,Junit4,我有一些异步代码,可能抛出JUnit未命中的异常(因此测试通过) 我创建了一个TestRule,将这些异常收集到一个列表中。任何测试完成后,断言将在列表上运行,如果异常列表非空,则测试将失败 我不希望在测试完成后失败,而是希望在异常发生时立即使测试失败。使用TestRule可以做到这一点吗 MyTestRule /** * Coroutines can throw exceptions that can go unnoticed by the JUnit Test Runner which w
TestRule
,将这些异常收集到一个列表中。任何测试完成后,断言将在列表上运行,如果异常列表非空,则测试将失败
我不希望在测试完成后失败,而是希望在异常发生时立即使测试失败。使用TestRule
可以做到这一点吗
MyTestRule
/**
* 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) }
}
}
/**
*协同路由可以抛出异常,这些异常可能会被将通过的JUnit测试运行程序忽略
*本应失败的测试。如果您使用
*[CoroutineContext]由[dispatcher]提供。
*/
类CoroutineExceptionRule:TestWatcher(),TestRule{
private val exceptions=Collections.synchronizedList(mutableListOf())
val调度程序:CoroutineContext
get()=Unconfined+CoroutineExceptionHandler{{uu0,throwable->
//我想挂接到测试生命周期中,并在这里立即使测试失败
例外情况。添加(可丢弃)
//此抛出不会总是通过测试。它至少会打印stacktrace
抛掷物
}
覆盖乐趣启动(说明:说明){
例外。清除()
}
覆盖已完成(说明:说明){
//而不是等待测试完成而失败
exceptions.forEach{throw AssertionError(it)}
}
}