-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp-sql_test.go
105 lines (91 loc) · 2.49 KB
/
app-sql_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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package db
import (
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/chadweimer/gomp/models"
"github.com/golang/mock/gomock"
)
func Test_AppConfiguration_Read(t *testing.T) {
type testArgs struct {
title string
dbError error
expectedError error
}
// Arrange
tests := []testArgs{
{"My App Title", nil, nil},
{"", sql.ErrNoRows, ErrNotFound},
{"", sql.ErrConnDone, sql.ErrConnDone},
}
for i, test := range tests {
t.Run(fmt.Sprint(i), func(t *testing.T) {
// Arrange
ctrl := gomock.NewController(t)
defer ctrl.Finish()
sut, dbmock := getMockDb(t)
defer sut.Close()
query := dbmock.ExpectQuery("SELECT \\* FROM app_configuration")
if test.dbError == nil {
query.WillReturnRows(sqlmock.NewRows([]string{"title"}).AddRow(test.title))
} else {
query.WillReturnError(test.dbError)
}
// Act
cfg, err := sut.AppConfiguration().Read()
// Assert
if !errors.Is(err, test.expectedError) {
t.Errorf("expected error: %v, received error: %v", test.expectedError, err)
}
if err := dbmock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
if test.expectedError == nil && cfg.Title != test.title {
t.Errorf("expected: '%s', received: '%s'", test.title, cfg.Title)
}
})
}
}
func Test_AppConfiguration_Update(t *testing.T) {
type testArgs struct {
title string
dbError error
expectedError error
}
// Arrange
tests := []testArgs{
{"My App Title", nil, nil},
{"", sql.ErrNoRows, ErrNotFound},
{"", sql.ErrConnDone, sql.ErrConnDone},
}
for i, test := range tests {
t.Run(fmt.Sprint(i), func(t *testing.T) {
// Arrange
ctrl := gomock.NewController(t)
defer ctrl.Finish()
sut, dbmock := getMockDb(t)
defer sut.Close()
dbmock.ExpectBegin()
exec := dbmock.ExpectExec("UPDATE app_configuration SET title = \\$1").WithArgs(test.title)
if test.dbError == nil {
exec.WillReturnResult(driver.RowsAffected(1))
dbmock.ExpectCommit()
} else {
exec.WillReturnError(test.dbError)
dbmock.ExpectRollback()
}
// Act
err := sut.AppConfiguration().Update(&models.AppConfiguration{Title: test.title})
// Assert
if !errors.Is(err, test.expectedError) {
t.Errorf("expected error: %v, received error: %v", test.expectedError, err)
}
if err := dbmock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
})
}
}