Skip to content

Commit 808cdc9

Browse files
committed
document time.Time argument matching example
1 parent f49a90b commit 808cdc9

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,46 @@ func TestShouldRollbackStatUpdatesOnFailure(t *testing.T) {
142142
}
143143
```
144144

145+
## Matching arguments like time.Time
146+
147+
There may be arguments which are of `struct` type and cannot be compared easily by value like `time.Time`. In this case
148+
**sqlmock** provides an [Argument](https://godoc.org/github.com/DATA-DOG/go-sqlmock#Argument) interface which
149+
can be used in more sophisticated matching. Here is a simple example of time argument matching:
150+
151+
``` go
152+
type AnyTime struct{}
153+
154+
// Match satisfies sqlmock.Argument interface
155+
func (a AnyTime) Match(v driver.Value) bool {
156+
_, ok := v.(time.Time)
157+
return ok
158+
}
159+
160+
func TestAnyTimeArgument(t *testing.T) {
161+
t.Parallel()
162+
db, mock, err := New()
163+
if err != nil {
164+
t.Errorf("an error '%s' was not expected when opening a stub database connection", err)
165+
}
166+
defer db.Close()
167+
168+
mock.ExpectExec("INSERT INTO users").
169+
WithArgs("john", AnyTime{}).
170+
WillReturnResult(NewResult(1, 1))
171+
172+
_, err = db.Exec("INSERT INTO users(name, created_at) VALUES (?, ?)", "john", time.Now())
173+
if err != nil {
174+
t.Errorf("error '%s' was not expected, while inserting a row", err)
175+
}
176+
177+
if err := mock.ExpectationsWereMet(); err != nil {
178+
t.Errorf("there were unfulfilled expections: %s", err)
179+
}
180+
}
181+
```
182+
183+
It only asserts that argument is of `time.Time` type.
184+
145185
## Run tests
146186

147187
go test -race

argument_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package sqlmock
2+
3+
import (
4+
"database/sql/driver"
5+
"testing"
6+
"time"
7+
)
8+
9+
type AnyTime struct{}
10+
11+
// Match satisfies sqlmock.Argument interface
12+
func (a AnyTime) Match(v driver.Value) bool {
13+
_, ok := v.(time.Time)
14+
return ok
15+
}
16+
17+
func TestAnyTimeArgument(t *testing.T) {
18+
t.Parallel()
19+
db, mock, err := New()
20+
if err != nil {
21+
t.Errorf("an error '%s' was not expected when opening a stub database connection", err)
22+
}
23+
defer db.Close()
24+
25+
mock.ExpectExec("INSERT INTO users").
26+
WithArgs("john", AnyTime{}).
27+
WillReturnResult(NewResult(1, 1))
28+
29+
_, err = db.Exec("INSERT INTO users(name, created_at) VALUES (?, ?)", "john", time.Now())
30+
if err != nil {
31+
t.Errorf("error '%s' was not expected, while inserting a row", err)
32+
}
33+
34+
if err := mock.ExpectationsWereMet(); err != nil {
35+
t.Errorf("there were unfulfilled expections: %s", err)
36+
}
37+
}

0 commit comments

Comments
 (0)