Skip to content

Instantly share code, notes, and snippets.

@mreichelt
Created March 31, 2022 11:58
Show Gist options
  • Save mreichelt/0ae80be8d32898ee4ffc6d4b22f1a00b to your computer and use it in GitHub Desktop.
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
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