Is it possible to use Spring from the Spring Exten...
# kotest
k
Is it possible to use Spring from the Spring Extension outside of a Spec like in the BeforeProject listeners to be able to do some setup stuff using the Spring constructs like the Spring Webclient etc ?
a
according to the use case, it should be possible. My use case is to delete all data from pg tables between specs, so I have this snippet:
Copy code
object DatabaseCleanerAfterSpecListener : AfterSpecListener {
    override suspend fun afterSpec(spec: Spec) {
        runCatching {
            val manager = TestContextManager(spec::class.java)
            val context = manager.testContext.applicationContext
            val jdbcTemplate = context.getBean(JdbcTemplate::class.java)
            GenericTestUtils.DataCleanerUtils.cleanData(
                jdbcTemplate,
                GenericTestUtils.AllTables.tablesList,
            )
        }
    }
}
hopefully it inspires a solution for you 🙂
k
Yes this works also the
BeforeSpecListener
as the Spring Context is available there. What I want to achieve though is to have a callback that runs only once for all Specs and this is a Listener like
BeforeProject
. Unfortunately the Spring Context is not available in that case
a
oh sorry, just realised you were looking for
beforeProject
, my bad. I guess that would be quite difficult, as Spring would not have been initialised by then. How about this, while we think on how/if to introduce it in kotest?
Copy code
object OnlyOnceBeforeSpecListener: BeforeSpecListener{
    var hasRun = false
    override suspend fun beforeSpec(spec: Spec) {
        if(hasRun) return
        runCatching {
            val manager = TestContextManager(spec::class.java)
            val context = manager.testContext.applicationContext
            val bean = context.getBean(WhateverYourBean::class.java)
        }.onFailure {
            println("this spec does not have spring context, not going to do anything")
        }.onSuccess {
            println("done with before spec setup")
            hasRun = true
        }
    }
}