...
1 package main
2
3 import (
4 "fmt"
5 "testing"
6
7 "github.com/DATA-DOG/go-sqlmock"
8 )
9
10
11 func TestShouldUpdateStats(t *testing.T) {
12 db, mock, err := sqlmock.New()
13 if err != nil {
14 t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
15 }
16 defer db.Close()
17
18 mock.ExpectBegin()
19 mock.ExpectExec("UPDATE products").WillReturnResult(sqlmock.NewResult(1, 1))
20 mock.ExpectExec("INSERT INTO product_viewers").WithArgs(2, 3).WillReturnResult(sqlmock.NewResult(1, 1))
21 mock.ExpectCommit()
22
23
24 if err = recordStats(db, 2, 3); err != nil {
25 t.Errorf("error was not expected while updating stats: %s", err)
26 }
27
28
29 if err := mock.ExpectationsWereMet(); err != nil {
30 t.Errorf("there were unfulfilled expectations: %s", err)
31 }
32 }
33
34
35 func TestShouldRollbackStatUpdatesOnFailure(t *testing.T) {
36 db, mock, err := sqlmock.New()
37 if err != nil {
38 t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
39 }
40 defer db.Close()
41
42 mock.ExpectBegin()
43 mock.ExpectExec("UPDATE products").WillReturnResult(sqlmock.NewResult(1, 1))
44 mock.ExpectExec("INSERT INTO product_viewers").
45 WithArgs(2, 3).
46 WillReturnError(fmt.Errorf("some error"))
47 mock.ExpectRollback()
48
49
50 if err = recordStats(db, 2, 3); err == nil {
51 t.Errorf("was expecting an error, but there was none")
52 }
53
54
55 if err := mock.ExpectationsWereMet(); err != nil {
56 t.Errorf("there were unfulfilled expectations: %s", err)
57 }
58 }
59
View as plain text