【问题标题】:Kotest beforeTest can not connect to database in a MicronautTestKotest beforeTest 无法连接到 MicronautTest 中的数据库
【发布时间】:2021-11-25 08:50:10
【问题描述】:

我在一个 Micronaut 项目中创建了 Kotest StringSpec 测试,并尝试清除数据库中的数据。

@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")
  }

}

this.template.prepareStatement 语句由于无法获取数据库连接的异常而失败。

【问题讨论】:

    标签: micronaut micronaut-data


    【解决方案1】:

    将 beforeTest 钩子包装到一个事务中以实现它。

    PostRepositoryTest的构造函数中注入一个TransactionOperatoions

    然后在回调中调用删除。

    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");
        }
    

    【讨论】:

      猜你喜欢
      • 2011-06-16
      • 2015-10-18
      • 2012-10-29
      • 2014-12-06
      • 2020-12-12
      • 1970-01-01
      相关资源
      最近更新 更多