kotlin multiplatform library simple http get request test

Viewed 330

I am new to kotlin multiplatform library. I wanted to make a simple HTTP get request and test if it works. here is what I have so far. this is in the commonMain package

import io.ktor.client.*
import io.ktor.client.request.*

object HttpCall {
    private val client: HttpClient = HttpClient()
    suspend fun request(url: String): String = client.get(url)
}

and here is my attempt to test

@Test
    fun should_make_http_call() {

        GlobalScope.launch {
            val response = HttpCall.request("https://stackoverflow.com/")
            println("Response: ->$response")
            assertTrue { response.contains("Stack Overflow - Where Developers Learn") }
            assertTrue { response.contains("text that does not exist on stackoverflow") }
        }

Now, this should fail because of the second assert but it doesn't. no matter what I do the test always passes. and printing the response does not work either what am I doing wrong here?

1 Answers

The test function will run in a single thread, and if the function ends without failing, the test passes. GlobalScope.launch starts an operation in a different thread. The main test thread will finish before the network calls get a chance to run.

You should be calling this with something like runBlocking, but testing coroutines in general, and ktor specifically, on Kotlin native, is not easy because there's no easy way to have the suspended function continue on your current thread.

Related