Suspending functions + unit tests An important pie...
# coroutines
j
Suspending functions + unit tests An important piece of my code was buggy but covered by a correct test ... that was ignored because I mistakenly use a suspending function in a JUnit class Gosh it would be so much better if suspending functions were supported directly in Junit instead of the
runTest { ... }
hack The issue is there https://github.com/junit-team/junit5/issues/1914 but very little happened since 3 years I created an issue, please star https://youtrack.jetbrains.com/issue/KT-52818/Provide-a-quick-fix-against-using-suspending-functions-in-Unit-Test
s
not sure if changing the test framework is an option for you, but #kotest supports suspend functions by default
j
I love kotest but here not really an option
👍 1
e
you can explore whether JUnit 5's extension system will allow you to handle suspend tests, but I suspect it's not possible
j
I guessed the issue above would be marked as fixed if that was possible 🙂
e
so I played around with it a little • the IDE already displays an error on
@kotlinx.test.Test suspend fun
• a JUnit5 extension could wrap every test in
runTest
and inject scope/continuation parameters, but it can't change test discovery, which means no way around JUnit ignoring all suspend funs
j
Importing
@Test
from
kotlin.test
doesn't work, it always import
org.unit.jupiter.api.Test
which doesn't give me the error, unless I expeclitely type
@kotlin.test.Test
which is not very convenient....
e
that error might be down to your IDE configuration; auto-complete allows both for me
I did think of a way to get JUnit to run suspend tests, though. it involves a couple of nested extensions, and isn't able to fully participate in the JUnit test lifecycle, but it is possible to write the following test:
Copy code
class ExampleTest : CoroutineTest {
    @Test
    suspend fun test() {
        println("OK")
    }
}
j
wow, thanks!
331 Views