https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
r

Riccardo Montagnin

03/05/2019, 9:49 AM
How do I test the fails of a test that relies on a
suspend
funciton? Let's consider this class
Copy code
/**
 * Allows the login of a user based on his private key.
 */
class PerformLoginUseCase internal constructor(private val repository: AuthenticationRepository){

    /**
     * Logs the user into the system using the given [authKey].
     * @return the user data once the login has been successful.
     */
    suspend operator fun invoke(authKey: PrivateKey): UserData {
        return repository.login(authKey)
    }
}
I have the following test
Copy code
@Test
fun useCaseThrowsExceptionWhenRepositoryDoes() {
    assertFailsWith(Throwable::class) {
        coEvery { repository.login(any()) } throws Throwable()
        GlobalScope.launch { performLogin(mockk()) }
    }
}
While this should work properly, it fails with an
assertionError
. I think the exception is not raised in time, so who should I do this?
g

gildor

03/05/2019, 10:03 AM
Because you run background job that return immediately and there is no chance for assertFailsWith catch it It’s like this code, there is no way to catch exception in this case too
Copy code
assertFailsWith(Throwable::class) {
   thread { error("Some error") }
}
use runBlocking instead of GlobalScope.launch
You shouldn’t use GlobalScope in tests (at least, I don’t see good use cases for this)
and to test suspend functions just use runBlocking (suspend
@Test
functions are not supported yet, but will be soon)
r

Riccardo Montagnin

03/05/2019, 10:07 AM
It's a common test, and I can't use the
runBlocking
method inside. I don't know why, but wit hthe following dependencies, it is not included:
Copy code
implementation deps.kotlin.stdlib.common
implementation deps.kotlinx.coroutines.common
implementation deps.kotlin.test.common
implementation deps.kotlin.test.annotations
implementation deps.kotlinx.coroutines.test
g

gildor

03/05/2019, 10:07 AM
runBlocking is not available in MPP
there are workarounds for this
also suspend test functions will be available in 1.3.30
r

Riccardo Montagnin

03/05/2019, 10:08 AM
Thank you very much. Any ETA on Kotlin 1.3.30?
g

gildor

03/05/2019, 10:09 AM
as usual, will be available when will be ready %)
but first EAP already available (not sure tho that KT-22228 is available there)
r

Riccardo Montagnin

03/05/2019, 10:09 AM
Thank you very much!
g

gildor

03/05/2019, 10:09 AM
but anyway, you can workaround it with expect/actual + dynamic type for JS
💯 1
2 Views