Search code examples
micronautmicronaut-data

Kotest beforeTest can not connect to database in a MicronautTest


I created a Kotest StringSpec test in a Micronaut project, and tried to clear data in the database.

@MicronautTest(environments = [Environment.TEST], startApplication = false)
class PostRepositoryTest(private val posts: PostRepository, private val template: JdbcOperations) : StringSpec({
   "a test" {//test includes database operations worked well.
    }
}){
    override fun beforeEach(testCase: TestCase) {
       val delCount = this.template.prepareStatement("delete from posts") { it ->
            it.executeUpdate()
       }
       print("deleting items: $delCount")
  }

}

The this.template.prepareStatement statement failed due to an exception of can not get a database connection.


Solution

  • Wrap the beforeTest hook into a transaction to make it.

    Inject a TransactionOperatoions in the constructor of PostRepositoryTest

    Then call the deletion in a callback.

    override fun beforeEach(testCase: TestCase) {
            val callback: TransactionCallback<Any, Int> = TransactionCallback { _: TransactionStatus<Any> ->
                val sql = "delete from posts";
                this.template.prepareStatement(sql) {
                    it.executeUpdate()
                }
            }
    
            val cnt = tx.executeWrite(callback)
            println("deleted $cnt");
        }