如何测试事务回滚并在Go lang中提交

I have such code:

tx, _ := db.Begin()
defer tx.Rollback()

err := db.Insert(foo)
err = db.Delete(bar)

if !err {
  tx.Commit()
}

and I don't have idea how to write 2 test cases:

  • successfull (data inserted and deleted)
  • error (nothing changes)

I was thinking about:

  • monkey patching by function injection to method which is doing db operations, and change this function in test
  • monkey patching by changing foo sql by making it global - I don't like it too much
  • make db not allowing delete operation for test time

Each of above options seems to be not ideal, how should I write this test cases?

Have a look at my library dbwrap https://github.com/metakeule/dbwrap that implements a driver.Driver, wrapping around another driver.

It also has a fake driver that you can use like this.

 package main

 import (
   "fmt"
   "github.com/metakeule/dbwrap"
 )

 var fake, db = dbwrap.NewFake()

 func q1() {
   fake.SetNumInputs(1)
   db.Query("Select ?", "hiho")
   q, v := fake.LastQuery()
   fmt.Println(q, v)
 }

Use the source code of fake.go as a starting point.