Created
March 31, 2022 11:58
-
-
Save mreichelt/0ae80be8d32898ee4ffc6d4b22f1a00b to your computer and use it in GitHub Desktop.
Kotlin Coroutines 1.6: run blocking test, but cancel scope at exit without caring about endless-running jobs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun TestCoroutineScope.runBlockingTest( | |
testBody: suspend TestCoroutineScope.() -> Unit, | |
) { | |
val regularEndOfTest = CancellationException() | |
try { | |
this.runBlockingTestKotlin { // import kotlinx.coroutines.test.runBlockingTest as runBlockingTestKotlin | |
testBody() | |
cancel(regularEndOfTest) | |
} | |
} catch (e: CancellationException) { | |
if (e !== regularEndOfTest) { | |
throw e | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment