While updating the Kotlin version from 1.7.10 to 1.9.10 Multiple test cases are failing

485 Views Asked by At

Issue Description

After updating the Kotlin version from 1.7.10 to 1.9.10, multiple tests are failing, and the primary issue is indicated by the error message:

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
1

There are 1 best solutions below

1
Balaji Dhanasekar On

To resolve this, we can write our own global uncaught exception handler and re throw the exception to JVM to handle it

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)

Also to add the rule in the test class

@get:Rule
    val throwRule = RethrowingExceptionHandler()