Kotlin多平台库简单http get请求测试

dced5bon  于 2022-12-19  发布在  Kotlin
关注(0)|答案(2)|浏览(174)

我是Kotlin多平台库的新手。我想做一个简单的HTTP get请求并测试它是否工作。下面是我目前所做的。这在commonMain包中

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)
}

这是我试图测试

@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") }
        }

现在,由于第二个Assert,它应该失败,但是它没有,无论我做什么,测试总是通过,并且打印响应也不起作用,我在这里做错了什么?

p5cysglq

p5cysglq1#

测试函数将在单个线程中运行,如果函数顺利结束,则测试通过。GlobalScope.launch将在另一个线程中启动操作。主测试线程将在网络调用有机会运行之前完成。
您 * 应该 * 使用类似runBlocking的命令调用它,但是在Kotlin本地机上测试协程(尤其是ktor)并不容易,因为没有简单的方法让挂起的函数在当前线程上继续。

6ljaweal

6ljaweal2#

我不会使用GlobalScoperunBlocking,因为它们不是真正为单元测试而设计的,而是使用runTest
步骤如下:

  • 检查您的build.gradle,确保在commontTest下确实有库'kotlinx-coroutines-test'集
val commonTest by getting {
   dependencies {
      implementation(kotlin("test"))
      implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:${Version.kotlinCoroutines}")
      ...
   }
}
  • 然后在目录commonTest中创建一个文件并运行
@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

相关问题