My case: in my personal kotlin project I use JUnit 5 for testing. And I have three test groups: unit tests, integration tests and end-to-end tests. Unit tests works fine as they don't require anything. Integration tests require database connection, and end-to-end tests require whole application context.
Implementation: All integration tests classes annotated with @ExtendsWith(DatabaseTestExt::class)
. DatabaseTestExt
implements BeforeEachCallback
(cleanup database before each test) and BeforeAllCallback
. In this callback I instanciate and put once resource that implements ExtensionContext.Store.CloseableResource
(because I have to close database connection and stop DI context before end of tests execution). Similar logic for end-to-end tests: start logging, start DI, launch web application.
Here's the short version of extension class. Full code can be found here.
class DatabaseTestExt : BeforeAllCallback, BeforeEachCallback, KoinComponent {
override fun beforeAll(context: ExtensionContext) {
context.getStore(ExtensionContext.Namespace.GLOBAL).getOrComputeIfAbsent("db") {
CloseableDatabase()
}
}
class CloseableDatabase : ExtensionContext.Store.CloseableResource {
init {
// initialize logging, DI and database logic
}
override fun close() {
// stop DI and database
}
}
override fun beforeEach(context: ExtensionContext) {
// clean up database
}
}
The problem: With such implementation JUnit creates and closes database resource in each test class. I want it to share resource between all tests annotated with @ExtendsWith(DatabaseTestExt::class)
, because ORM instantiation is not cheap it terms of time.
I thought about using context.root.getStore()
instead of context.getStore()
, but then it looks like context lifecycle ends in the end of the whole test suite, and this is not good for my case because DI initialization from DatabaseTestExt
conflicts with EndToEndTestExt
.
So, is it possible to share resource between test classes that uses same JUnit extension in JUnit 5? If not, can you suggest some testing frameworks that supports such logic?
Thank you.
P.S.: I thought about posting this on sqa.stackexchange.com, but decided to post it here at first.
Aucun commentaire:
Enregistrer un commentaire