Tom Yuval
08/31/2022, 1:56 PMsuspend
functions, so I’m using kotlinx.coroutines.test.runTest
.
This has the useful feature of skipping `delay`s and simulating actual scheduling with virtual time, which is super useful as it allows the tests to run fast, and one can also control the order of execution of various parts of different coroutines very delicately.
However, I have a very specific use case where functions under test use `delay`s, and I actually want the `delay`s to execute for real, just like they would in production (this shouldn’t normally be required in pure unit tests, but is necessary in my case as the functions I’m testing interact with other systems). Is there a way to do that?mkrussel
08/31/2022, 1:58 PMrunBlocking
instead of runTest
if you really want to delay.
But if you want to control the delays instead of actually delaying, you may want to look at https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-standard-test-dispatcher.htmlTom Yuval
08/31/2022, 2:26 PMrunBlocking
because, at least in some cases, I’m targeting JS…Tom Yuval
08/31/2022, 2:29 PMStandardTestDispatcher
?
Currently my code look something like:
@Test
fun testSomething() = runTest {
performTests()
}
How do I rewrite that to use StandardTestDispatcher
?mkrussel
08/31/2022, 4:59 PMephemient
08/31/2022, 5:01 PM@Test
suspend fun testSomething() {
}
or
@Test
fun testSomething() = GlobalScope.promise {
}
and get real delaysTom Yuval
09/01/2022, 7:21 AM@Test suspend fun
does not seem to work (it fails to even compile: Unsupported [suspend test functions]
).
2. GlobalScope.promise
seems to do exactly what I need – thanks! 👍ephemient
09/01/2022, 4:23 PM// common
expect fun runRealTest(context: CoroutineContext = EmptyCoroutineContext, testBody: suspend () -> Unit): TestResult
// JS
actual fun runRealTest(context: CoroutineContext, testBody: suspend () -> Unit) = GlobalScope.promise(context) { testBody() }
// other
actual fun runRealTest(context: CoroutineContext, testBody: suspend () -> Unit) = runBlocking(context) { testBody() }