From 808cdc9973787bc4d423563529b628a1b31068de Mon Sep 17 00:00:00 2001 From: gedi Date: Thu, 4 Feb 2016 09:42:49 +0200 Subject: [PATCH] document time.Time argument matching example --- README.md | 40 ++++++++++++++++++++++++++++++++++++++++ argument_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 argument_test.go diff --git a/README.md b/README.md index 2cc06a9..cbec043 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,46 @@ func TestShouldRollbackStatUpdatesOnFailure(t *testing.T) { } ``` +## Matching arguments like time.Time + +There may be arguments which are of `struct` type and cannot be compared easily by value like `time.Time`. In this case +**sqlmock** provides an [Argument](https://godoc.org/github.com/DATA-DOG/go-sqlmock#Argument) interface which +can be used in more sophisticated matching. Here is a simple example of time argument matching: + +``` go +type AnyTime struct{} + +// Match satisfies sqlmock.Argument interface +func (a AnyTime) Match(v driver.Value) bool { + _, ok := v.(time.Time) + return ok +} + +func TestAnyTimeArgument(t *testing.T) { + t.Parallel() + db, mock, err := New() + if err != nil { + t.Errorf("an error '%s' was not expected when opening a stub database connection", err) + } + defer db.Close() + + mock.ExpectExec("INSERT INTO users"). + WithArgs("john", AnyTime{}). + WillReturnResult(NewResult(1, 1)) + + _, err = db.Exec("INSERT INTO users(name, created_at) VALUES (?, ?)", "john", time.Now()) + if err != nil { + t.Errorf("error '%s' was not expected, while inserting a row", err) + } + + if err := mock.ExpectationsWereMet(); err != nil { + t.Errorf("there were unfulfilled expections: %s", err) + } +} +``` + +It only asserts that argument is of `time.Time` type. + ## Run tests go test -race diff --git a/argument_test.go b/argument_test.go new file mode 100644 index 0000000..e351f20 --- /dev/null +++ b/argument_test.go @@ -0,0 +1,37 @@ +package sqlmock + +import ( + "database/sql/driver" + "testing" + "time" +) + +type AnyTime struct{} + +// Match satisfies sqlmock.Argument interface +func (a AnyTime) Match(v driver.Value) bool { + _, ok := v.(time.Time) + return ok +} + +func TestAnyTimeArgument(t *testing.T) { + t.Parallel() + db, mock, err := New() + if err != nil { + t.Errorf("an error '%s' was not expected when opening a stub database connection", err) + } + defer db.Close() + + mock.ExpectExec("INSERT INTO users"). + WithArgs("john", AnyTime{}). + WillReturnResult(NewResult(1, 1)) + + _, err = db.Exec("INSERT INTO users(name, created_at) VALUES (?, ?)", "john", time.Now()) + if err != nil { + t.Errorf("error '%s' was not expected, while inserting a row", err) + } + + if err := mock.ExpectationsWereMet(); err != nil { + t.Errorf("there were unfulfilled expections: %s", err) + } +}