Skip to content

Instantly share code, notes, and snippets.

@wickedev
Last active February 12, 2021 07:13
Show Gist options
  • Save wickedev/feaf8fc6794ef1b96a1490cb983d0b4f to your computer and use it in GitHub Desktop.
Save wickedev/feaf8fc6794ef1b96a1490cb983d0b4f to your computer and use it in GitHub Desktop.
testcontainer + spring-data-r2dbc + spek + kotlin coroutine
class DatabaseContainer(spek: LifecycleAware) {
private val connectionFactory = ConnectionFactories.get("r2dbc:tc:postgresql:///test?TC_IMAGE_TAG=13")
private val repositoryFactory by spek.memoized {
val operations = R2dbcEntityTemplate(connectionFactory)
R2dbcRepositoryFactory(operations)
}
fun create() {
runBlocking {
connectionFactory.create().awaitFirstOrNull()
}
}
fun destroy() {
if (connectionFactory is Closeable) {
runBlocking {
connectionFactory.close().awaitFirstOrNull()
}
}
}
fun <T> getRepository(repositoryInterface: Class<T>): T {
return repositoryFactory.getRepository(repositoryInterface)
}
fun populate(vararg scriptPaths: String) {
val populator = CompositeDatabasePopulator(
scriptPaths.map {
ResourceDatabasePopulator(
ClassPathResource(it)
)
}
)
runBlocking {
populator.populate(connectionFactory).awaitFirstOrNull()
}
}
}
class DummyRepositoryTest : Spek({
val database = DatabaseContainer(this)
val dummyRepository by memoized {
database.getRepository(DummyRepository::class.java)
}
beforeEachTest {
database.create()
database.populate("db/ddl.sql")
}
afterEachTest {
database.destroy()
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment