What is the current preferred method to test funct...
# test
t
What is the current preferred method to test functions in commonMain that can take some time, like API calls? On the Android side I fund the CountDownLatch/.await works well. Is there a similar approach using coroutines test that I can use in commonTest? Thank you!
c
What behavior are you trying to test, exactly? If you want to test the returned value, you can just
suspend
until the function finishes.
t
I am making an API call, which is defined as having a trailing closure. So something like:
Copy code
apiCall(param1, param2) { success, exception ->
}
note it is not defined as suspend. So I just need to know how I can "suspend until the function finishes".
c
You can use https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/suspend-coroutine.html to convert a callback API to
suspend
:
Copy code
suspend fun apiCallSync(param1: …, param2: …): T {
    return suspendCoroutine { cont ->
        apiCall(param1, param2) { success, exception ->
           if (success != null) cont.resume(success)
           else cont.resumeWithException(exception)
        }
    }
}
t
Ah, very nice! So suspendCoroutine was the magic I was looking for. Thank you so much!
c
No problem 🙂
If you have a way to cancel the request, you may also be interested in https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/suspend-cancellable-coroutine.html If it's only in tests, it probably won't matter—but if you're using this in production code,
suspendCancellableCoroutine
is better
👍 1