使用 Spock 对 Jooby 应用程序进行集成测试

integration testing of Jooby application using Spock

我有一个非常简单的应用程序,它使用 Jooby 作为网络框架。它 class 负责 REST 看起来像这样

class Sandbox : Kooby ({
    path("/sandbox") {
        get {
            val environment = require(Config::class).getString("application.env")
            "Current environment: $environment"
        }

        get ("/:name") {
            val name = param("name")
            "Auto response $name"
        }
    }
})

我想为它编写集成测试。我的测试看起来像这样。我使用 spockrest-assured。问题是我没有应用程序 运行ning 并且想 运行 使用某种嵌入式服务器或其他任何东西来 运行 它。怎么做?

我的简单测试是这样的

class SandboxTest extends Specification {

    def "check current environment"() {
        given:
            def request = given()
        when:
            def response = request.when().get("/sandbox")
        then:
            response.then().statusCode(200) // for now 404
    }
}

您需要在 Spock 中寻找 before/after 测试(或 class)挂钩。在 before 钩子中启动 Jooby 而不会阻塞线程:

app.start("server.join=false")

在后钩中:

app.stop();

从未使用过 Spock,但这是 Spek 的一个小扩展方法:

fun SpecBody.jooby(app: Jooby, body: SpecBody.() -> Unit) {
  beforeGroup {
    app.start("server.join=false")
  }

  body()

  afterGroup {
    app.stop()
  }
}

最后来自你的测试:

@RunWith(JUnitPlatform::class)
object AppTest : Spek({
  jooby(App()) {
    describe("Get with query parameter") {
        given("queryParameter name=Kotlin") {
            it("should return Hello Kotlin!") {
                val name = "Kotlin"
                given()
                        .queryParam("name", name)
                        .`when`()
                        .get("/")
                        .then()
                        .assertThat()
                        .statusCode(Status.OK.value())
                        .extract()
                        .asString()
                        .let {
                            assertEquals(it, "Hello $name!")
                        }
            }
         ...
      ...
   ...
...

Maven Spek example

Gradle Spek example