-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction_test.go
61 lines (51 loc) · 1.27 KB
/
transaction_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package orm
import (
"context"
"database/sql"
"github.com/DATA-DOG/go-sqlmock"
"github.com/stretchr/testify/assert"
"testing"
)
func TestTx_Commit(t *testing.T) {
// *sql.DB, Sqlmock, error
mockDB, mock, err := sqlmock.New()
if err != nil {
t.Fatal(err)
}
defer func() { _ = mockDB.Close() }()
db, err := OpenDB("mysql", mockDB)
if err != nil {
// t.Fatal: 不单报告单元测试已经失败,而且会向测试输出写入一些消息,
// 然后立刻停止这个测试函数的执行(如果还有其他的测试函数,会继续执行其他的测试函数)
t.Fatal(err)
}
defer func() {
mock.ExpectClose()
_ = db.Close()
}()
// 事务正常提交 表示mock 事务的开始和结束
mock.ExpectBegin()
mock.ExpectCommit()
tx, err := db.BeginTx(context.Background(), &sql.TxOptions{})
assert.Nil(t, err)
err = tx.Commit()
assert.Nil(t, err)
}
func TestTx_Rollback(t *testing.T) {
mockDB, mock, err := sqlmock.New()
if err != nil {
t.Fatal(err)
}
defer func() { _ = mockDB.Close() }()
db, err := OpenDB("mysql", mockDB)
if err != nil {
t.Fatal(err)
}
// 事务回滚
mock.ExpectBegin()
mock.ExpectRollback()
tx, err := db.BeginTx(context.Background(), &sql.TxOptions{})
assert.Nil(t, err)
err = tx.Rollback()
assert.Nil(t, err)
}