How to test transaction rollback and commit in go lang

huangapple go评论86阅读模式
英文:

How to test transaction rollback and commit in go lang

问题

我有这样的代码:

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

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

if !err {
  tx.Commit()
}

我不知道如何编写两个测试用例:

  • 成功的情况(数据插入和删除)
  • 错误的情况(没有任何更改)

我在考虑:

  • 通过函数注入来进行猴子补丁,修改执行数据库操作的方法,并在测试中更改此函数
  • 通过将 foo 的 SQL 改为全局变量来进行猴子补丁 - 我不太喜欢这种方法
  • 在测试期间使数据库不允许删除操作

以上每个选项似乎都不是理想的,我应该如何编写这些测试用例?

英文:

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?

答案1

得分: 1

请看一下我的库dbwrap https://github.com/metakeule/dbwrap,它实现了一个driver.Driver,可以包装另一个驱动程序。

它还有一个你可以这样使用的虚拟驱动程序。

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

使用fake.go的源代码作为起点。

英文:

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 <code>fake.go</code> as a starting point.

huangapple
  • 本文由 发表于 2014年5月15日 00:46:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/23660549.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定