1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks.I get it now
0

I will not use the GlobalScope or the runBlocking because they are not really made for Unit Test. Instead, I will use runTest.

Here are the steps:

  • Check your build.gradle and make sure you do have under commontTest the lib 'kotlinx-coroutines-test' set
val commonTest by getting {
   dependencies {
      implementation(kotlin("test"))
      implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:${Version.kotlinCoroutines}")
      ...
   }
}
  • Then into your directory commonTest, create a file and run
@Test
fun should_make_http_call() = runTest {
   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") }
}

Extra: runTest does not handle exceptions very well, so if you are interested in making to catch any exceptions if happens. Change runTest for runReliableTest, You can get the code from this link https://github.com/Kotlin/kotlinx.coroutines/issues/1205#issuecomment-1238261240

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.