-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdb_test.go
More file actions
71 lines (59 loc) · 1.83 KB
/
db_test.go
File metadata and controls
71 lines (59 loc) · 1.83 KB
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
62
63
64
65
66
67
68
69
70
71
package sqlxchain
import (
"fmt"
"testing"
"github.com/jmoiron/sqlx"
"gopkg.in/DATA-DOG/go-sqlmock.v1"
)
func setupChain(t *testing.T) (SqlxChain, sqlmock.Sqlmock) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
chain := SqlxChain{Db: sqlx.NewDb(db, "mock")}
return chain, mock
}
// a successful case
func TestShouldCommit(t *testing.T) {
chain, mock := setupChain(t)
defer chain.Db.Close()
mock.ExpectBegin()
mock.ExpectExec("UPDATE products").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectExec("INSERT INTO product_viewers").WithArgs(2, 3).WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()
// now we execute our method
if err := chain.Context().Begin().
Exec("UPDATE products").
Exec("INSERT INTO product_viewers", 2, 3).
Commit().
Err(); err != nil {
t.Errorf("error was not expected while updating: %s", err)
}
// we make sure that all expectations were met
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expections: %s", err)
}
}
// a failing test case
func TestShouldRollbackOnFailure(t *testing.T) {
chain, mock := setupChain(t)
defer chain.Db.Close()
mock.ExpectBegin()
mock.ExpectExec("UPDATE products").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectExec("INSERT INTO product_viewers").
WithArgs(2, 3).
WillReturnError(fmt.Errorf("some error"))
mock.ExpectRollback()
// now we execute our method
if err := chain.Context().Begin().
Exec("UPDATE products").
Exec("INSERT INTO product_viewers", 2, 3).
Commit().
Err(); err == nil {
t.Errorf("error was expected while updating")
}
// we make sure that all expectations were met
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expections: %s", err)
}
}