I am using Spek2 which spawns an embedded server (...
# spek
f
I am using Spek2 which spawns an embedded server (running on a different thread). I want this server to be up and running while executing all tests but shut down after finishing all tests. Normally (in junit 5 or testng), i would do something like this when i create the server.
Copy code
fun getOrCreateServer() {
    ...
    Runtime.getRuntime().addShutdownHook(Thread(Runnable {
        server.shutdown();
    }))
    return server
}
Then in my tests, I would just call this method to get the server instance and do stuff with it. Then after all tests have executed, this would be called to shutdown the server In Spek2, this does not get called How do I what I want to do in Spek2? 🙂
r
Hey! Maybe something like this:
Copy code
val server by memoized(CachingMode.SCOPE) { ... }

...

afterGroup { server.shutdown() }
Alternatively,
memoized
accepts a
destructor
parameter - which will be called when the memoized object is not needed anymore.
f
in junit (for example), i dont put
server.shutdown()
in the teardown (i.e. afterGroup). Instead, when i start the server, I add the
server.shutdown()
in the JVM shutdown hook. That's because i want to start the server once for ALL the tests, and shut it down once ALL the tests are done If I put the shutdown in the teardown, it will start and stop the server for every test suite.
r
Right, there are a few cases where shutdown hooks won't work. IIRC, JUnit calls
System.exit(0)
after all tests are finish - because lingering non-daemon threads can block the jvm from shutting down (which can cause the shutdown hooks not to be called).
f
Actually, after doing some more work, looks like the shutdown hook does get call when running spek from gradle. but it does not when running it using intellij's spek framework plugin