【问题标题】:integration testing of Jooby application using Spock使用 Spock 对 Jooby 应用程序进行集成测试
【发布时间】:2019-01-22 09:42:07
【问题描述】:

我有一个非常简单的应用程序,它使用Jooby 作为网络框架。它负责 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。问题是我没有运行应用程序,而是想使用某种嵌入式服务器或其他方式运行它。该怎么做?

我的简单测试是这样的

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

【问题讨论】:

    标签: rest kotlin spock jooby


    【解决方案1】:

    您需要在 Spock 中寻找测试(或类)之前/之后的钩子。在 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 2021-04-15
      • 2013-10-10
      • 1970-01-01
      • 2023-03-11
      • 2022-08-03
      相关资源
      最近更新 更多