如何始终使用原始服务器设置来测试 Ktor 服务器?

问题描述 投票:0回答:0

假设我需要测试用 ktor 制作的 API,如下所示:

import kotlin.test.Test


class MyTests {

  @Test
  fun testGet() {
    //...
  }

  @Test
  fun testPost() {
    //...
  }

  @Test
  fun testPut() {
    //...
  }

  @Test
  fun testDelete() {
    //...
  }
}

我试图将每个测试视为彼此隔离且独立的东西。在这种情况下,每个测试都应该从头开始有自己的设置,例如:

  @Test
  fun testPost() = testSuspend {
    val testServer = TestApplicationEngine(createTestEnvironment {
      developmentMode = false
      module {
        configureRouting()
        configureSerialization()
      }
    })

    val testClient = testServer.client.config {
      install(ContentNegotiation) {
        json()
      }
    }
    testServer.start(wait = false)

    val targetCredentials = Credentials("myName", "123")
    val postResponse = testClient.post("/api/users") {
      contentType(ContentType.Application.Json)
      setBody(targetCredentials)
    }
    val uuid = postResponse.body<String>()

    val getUserResponse = testClient.get("/api/users/${uuid}")
    val receivedUser = getUserResponse.body<User>()

    assertEquals(HttpStatusCode.OK, getUserResponse.status)
    assertEquals(targetCredentials.username, receivedUser.credentials!!.username)

    testServer.stop()
    testServer.cancel()
    testClient.cancel()
  }

这非常奇怪,但我没有让测试单独工作,甚至像这样在本地手动创建变量。

我目前正在通过使用本地静态用户列表作为数据库来测试这一点,我知道在某些概念上这是一个不好的做法,但我正在研究 ktor 结构。我认为即使我之前在另一个@Test结束时以编程方式“关闭”服务器/客户端,总是会开始一个新的@Test,由于某种原因,本地用户列表数据保持活动状态,服务器似乎没有被完全处置或其他什么像那样。例如,同时运行上面的测试和下面的测试,无法创建,因为它已经存在:

@Test
fun testGetUser() = testSuspend {
        val testServer = TestApplicationEngine(createTestEnvironment {
          developmentMode = false
          module {
            configureRouting()
            configureSerialization()
          }
        })

        val testClient = testServer.client.config {
          install(ContentNegotiation) {
            json()
          }
        }

        testServer.start(wait = false)

        val targetCredentials = Credentials("myName", "123")

        val postResponse = testClient.post("/api/users") {
          contentType(ContentType.Application.Json)
          setBody(targetCredentials)
        }

        val uuid = postResponse.body<String>()

        val getUserResponse = testClient.get("/api/users/${uuid}")

        val receivedUser = getUserResponse.body<User>()

        assertEquals(HttpStatusCode.OK, getUserResponse.status)
        assertEquals(targetCredentials.username, receivedUser.credentials!!.username)

        testServer.stop()
        testServer.cancel()
        testClient.cancel()
}

处理各个测试的最佳方法是怎样的?

api kotlin server client ktor
© www.soinside.com 2019 - 2024. All rights reserved.