Documentation
¶
Overview ¶
Package dbtesting provides handy tools for using with databases.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var OkValue = okValue{}
OkValue is used for sqlmock package for when the checks should always return true.
Functions ¶
This section is empty.
Types ¶
type Mocha ¶
type Mocha struct {
Out io.Writer // if not set it will print to stdout
// contains filtered or unexported fields
}
Mocha prints spec reports in terminal.
type ValueRecorder ¶
type ValueRecorder interface {
// Record records the value of the value the first time it sees it. It panics
// if the value is already been recorded.
Record(name string) sqlmock.Argument
// For reuses the value in the query. It panics if the value is not been
// recorded.
For(name string) sqlmock.Argument
// Value returns the recorded value of the item. It panics if the value is not
// been recorded.
Value(name string) any
}
ValueRecorder records the values when they are seen and compares them when they are asked. You can create a new ValueRecorder with NewValueRecorder function. Values should have one Record call and zero or more For calls.
Example ¶
db, mock, err := sqlmock.New()
if err != nil {
panic(err)
}
defer db.Close()
defer func() {
if err := mock.ExpectationsWereMet(); err != nil {
fmt.Printf("there were unfulfilled expectations: %s", err)
}
}()
rec := dbtesting.NewValueRecorder()
mock.ExpectExec("INSERT INTO life .+").
WithArgs(rec.Record("truth")).
WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectExec("INSERT INTO reality .+").
WithArgs(rec.For("truth")).
WillReturnResult(sqlmock.NewResult(1, 1))
// pretend the following query happens in another package and the argument is
// totally random.
_, err = db.Exec("INSERT INTO life (name) VALUE ($1)", 666)
fmt.Println("Error:", err)
// say we don't have access to the value and we don't know what value would be
// passed, but it is important the value is the same as the logic has to pass.
_, err = db.Exec("INSERT INTO reality (name) VALUE ($1)", 666)
fmt.Println("Error:", err)
fmt.Printf("got recorded value: %d", rec.Value("truth"))
Output: Error: <nil> Error: <nil> got recorded value: 666
Example (Value) ¶
db, mock, err := sqlmock.New()
if err != nil {
panic(err)
}
defer db.Close()
defer func() {
if err := mock.ExpectationsWereMet(); err != nil {
fmt.Printf("there were unfulfilled expectations: %s", err)
}
}()
rec := dbtesting.NewValueRecorder()
mock.ExpectExec("INSERT INTO life .+").
WithArgs(rec.Record("meaning")).
WillReturnResult(sqlmock.NewResult(1, 1))
_, err = db.Exec("INSERT INTO life (name) VALUE ($1)", 42)
fmt.Println("Error:", err)
fmt.Printf("Meaning of life: %d", rec.Value("meaning").(int64))
Output: Error: <nil> Meaning of life: 42
func NewValueRecorder ¶
func NewValueRecorder() ValueRecorder
NewValueRecorder returns a fresh ValueRecorder instance.
Click to show internal directories.
Click to hide internal directories.