Kotlin / Ktor,不能使用 withtTestApplication 因为我的 main 是一个挂起函数

Kotlin / Ktor, cant use withtTestApplication because my main is a suspend function

我的主图是这样的

suspend fun main(testing: Boolean = false) {

    // do some db related stuff with coroutines
    dbSetupRun() // this is using coroutines
    embeddedServer(Netty, 8080) {
       ...
     }.start(wait = true}

我的测试代码看起来像

  @Test
  suspend fun `test` () {
  
  withTestApplication({ main(testing = true) }) {
            handleRequest(HttpMethod.Get, "${config.root}/${config.version}/test").apply {
              assertEquals(HttpStatusCode.OK, response.status())
              assertEquals(response, content)

}

但是我收到一条错误消息,指出该代码 Suspend function 'main' should be called only from a coroutine or another suspend function

我很困惑我应该如何处理这个

您应该将 main 函数调用包装到协程构建器中,例如 runBlocking(建议用于测试)。

withTestApplication({ runBlocking { main(testing = true) } })