But it doesn’t work if the `withTestApplication` b...
# ktor
c
But it doesn’t work if the
withTestApplication
block is at a higher level. It would be nice to be able to create the TestEngine once (e.g. at the
given("an application")
level) and use it in multiple
on
/
it
contexts.
o
I don’t think it is about reusing. It looks like Spek and Ktor DSLs intersect in some way and test engine is stopped too early. May be you need to unroll
withTestApplication
function and integrate it with Spek lifecycles
d
You could use
val application by memoized { withTestApplication... }
I guess.
The test discovery stage runs all the code outside the `it`s and then runs them in the actual testing mode, so in cause a few funny situations... memoized recreates the instance before the actual teat according to what you provide in it's parameter.
The thing is that the `handeRequest`s might need to be inside the
withTestApplication
lambda... I don't think there's such a function outside of it, but I could be wrong.
c
To follow up on this, the following works:
Copy code
kotlin
object AppSpec : Spek({
    given("an application") {
        val engine = TestApplicationEngine(createTestEnvironment())

        beforeGroup {
            engine.start()
            engine.application.mainModule()
        }

        afterGroup {
            engine.stop(0L, 0L, TimeUnit.MILLISECONDS)
        }

        with(engine) {
            on("/v1/ping") {
                it("should return pong") {
                    with(handleRequest(HttpMethod.Get, "/v1/ping")) {
                        assertEquals("pong", response.content)
                    }
                }
            }

            on("/v2/ping") {
                it("should return pong") {
                    with(handleRequest(HttpMethod.Get, "/v2/ping")) {
                        assertEquals("pong", response.content)
                    }
                }
            }
        }
    }
})
The first test takes 100--200ms, following tests take 5--10ms---so there’s definitely a benefit to doing it this way (as opposed to starting a new TestApplicationEngine for every test)
o
Yep, but honestly even 100ms for a complete web test environment is not bad at all 😉
c
It’s not! They just would add up 🙂