dongliang1654 2017-07-11 08:42
浏览 81

如何测试使用数据库(MySQL)的Go代码?

I have a gRPC service using MySQL and need to clear records after every test case. I try to wrap every test case with a transaction. It works if there's no transaction in my rpc code but fails if there are. And there'll be errors like:

can't start transaction
...
sql: Transaction has already been committed or rolled back

Then I try to use truncate to clear the records but some of the test cases fails randomly.

My code is like(I use gorm):

func foo(db *gorm.DB) {
    tx := db.Begin()
    // query and insert
    tx.Commit()
}
// Use transaction to do database cleanup
func TestFooVersion1() {
    testDB := initDB()
    tx = testDB.Begin() // setup
    foo(testDB)
    tx.Rollback() // teardown
}
// Use truncate to do database cleanup
func TestFooVersion2() {
    testDB := initDB()
    foo(testDB)
    truncateTables(testDB) // teardown
}
func truncateTables(db *gorm.DB) {
    // exec "TRUNCATE TABLE table;" for every table
}

What's a proper way to test the code using DB(MySQL)? (I don't like mock like go-sqlmock)

  • 写回答

2条回答 默认 最新

  • douqiandai4327 2017-07-11 13:28
    关注

    It's hard to say without seeing code, but based on the error it sounds like you're sharing a connection between multiple tests, and each one is trying to start a transaction. Make sure that each test open its own connection, starts its own transaction, and when it is finished, commits or rolls back and closes the connection.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作