将 Kotlin 版本从 1.7.10 更新到 1.9.10 时,多个测试用例失败

问题描述 投票:0回答:1

问题描述

Kotlin 版本从 1.7.10 更新到 1.9.10 后,多次测试均失败,主要问题是错误消息:

kotlinx.coroutines.test.UncaughtExceptionsBeforeTest: There were uncaught exceptions before the test started. Please avoid this, as such exceptions are also reported in a platform-dependent manner so that they are not lost.
kotlinx.coroutines.test.UncaughtExceptionsBeforeTest: There were uncaught exceptions before the test started. Please avoid this, as such exceptions are also reported in a platform-dependent manner so that they are not lost.
at app//kotlinx.coroutines.test.TestScopeImpl.enter(TestScope.kt:242)
at app//kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt.runTest-8Mi8wO0(TestBuilders.kt:307)
at app//kotlinx.coroutines.test.TestBuildersKt.runTest-8Mi8wO0(Unknown Source)
at app//kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt.runTest-8Mi8wO0(TestBuilders.kt:166)
at app//kotlinx.coroutines.test.TestBuildersKt.runTest-8Mi8wO0(Unknown Source)
at app//kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt.runTest-8Mi8wO0$default(TestBuilders.kt:158)
at app//kotlinx.coroutines.test.TestBuildersKt.runTest-8Mi8wO0$default(Unknown Source)

Below are the mocking lib versions
- Mockk version -  1.13.8
- Mockito version - 5.6.0
- org.jetbrains.kotlinx:kotlinx-coroutines-test - 1.7.3
android unit-testing junit kotlin-coroutines mockk
1个回答
0
投票

为了解决这个问题,我们可以编写自己的全局未捕获异常处理程序,并将异常重新抛出给 JVM 来处理它

class RethrowingExceptionHandler : TestRule, Thread.UncaughtExceptionHandler {
    override fun uncaughtException(
        thread: Thread,
        throwable: Throwable
    ): Nothing = throw UncaughtException(throwable)

    override fun apply(base: Statement, description: Description): Statement {
        return object : Statement() {
            @Throws(Throwable::class)
            override fun evaluate() {
            }
        }
    }
}

internal class UncaughtException(cause: Throwable) : Exception(cause)

还要在测试类中添加规则

@get:Rule
    val throwRule = RethrowingExceptionHandler()
© www.soinside.com 2019 - 2024. All rights reserved.