restkotlinspockjooby

integration testing of Jooby application using Spock


I've got pretty simple application that uses Jooby as web framework. Its class responsible for REST looks like this

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

I want to write integration test for it. My test looks like this. I use spock and rest-assured. The thing is that I don't have the application running and want to run it using some kind of embedded server or whatever. How to do that?

My simple test looks like this

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

Solution

  • You need to look for before/after test (or class) hooks in Spock. In the before hook you start Jooby without blocking the thread:

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

    in the after hook:

    app.stop();
    

    Never used Spock but here is a small extension method for Spek:

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

    Finally from your test:

    @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