Kotest beforeTest 无法连接到 MicronautTest 中的数据库
Kotest beforeTest can not connect to database in a MicronautTest
我在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
语句由于无法获取数据库连接异常而失败。
将 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");
}
我在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
语句由于无法获取数据库连接异常而失败。
将 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");
}