1
0
mirror of https://github.com/DATA-DOG/go-sqlmock.git synced 2025-06-19 00:07:38 +02:00
Files
examples
basic
basic.go
basic_test.go
blog
orders
doc.go
.gitignore
.travis.yml
LICENSE
README.md
argument.go
argument_test.go
driver.go
driver_test.go
expectations.go
expectations_before_go18.go
expectations_go18.go
expectations_go18_test.go
expectations_test.go
go.mod
options.go
query.go
query_test.go
result.go
result_test.go
rows.go
rows_go13_test.go
rows_go18.go
rows_go18_test.go
rows_test.go
sqlmock.go
sqlmock_go18.go
sqlmock_go18_19.go
sqlmock_go18_test.go
sqlmock_go19.go
sqlmock_go19_test.go
sqlmock_test.go
statement.go
statement_test.go
stubs_test.go
go-sqlmock/examples/basic/basic_test.go

59 lines
1.6 KiB
Go
Raw Normal View History

package main
import (
"fmt"
"testing"
"github.com/DATA-DOG/go-sqlmock"
)
// a successful case
func TestShouldUpdateStats(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
mock.ExpectBegin()
mock.ExpectExec("UPDATE products").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectExec("INSERT INTO product_viewers").WithArgs(2, 3).WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()
// now we execute our method
if err = recordStats(db, 2, 3); err != nil {
t.Errorf("error was not expected while updating stats: %s", err)
}
// we make sure that all expectations were met
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
// a failing test case
func TestShouldRollbackStatUpdatesOnFailure(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
mock.ExpectBegin()
mock.ExpectExec("UPDATE products").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectExec("INSERT INTO product_viewers").
WithArgs(2, 3).
WillReturnError(fmt.Errorf("some error"))
mock.ExpectRollback()
// now we execute our method
if err = recordStats(db, 2, 3); err == nil {
t.Errorf("was expecting an error, but there was none")
}
// we make sure that all expectations were met
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}