-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
gorm.DB mocking for Unit Testing #1525
Comments
Because go's type system is not covariant\contrvariant. Find(interface {}, ...interface {}) *gorm.DB is not Find(interface {}, ...interface {}) IDatabase, even if *gorm.DB implemented IDatabase interface. |
i will find a tdd solution for gorm now. and i think we need a mock sql.Database implemention ? |
@smikulcik @mykytanikitenko @imiskolee @sunfmin @levinalex |
👍 for adding a db mock for use in (Unit) tests. Would something like Anyway, currently, as others stated, mocks can be implemented with https://github.com/DATA-DOG/go-sqlmock like: import (
"github.com/jinzhu/gorm"
"gopkg.in/DATA-DOG/go-sqlmock.v1"
)
...
func TestMyGoodness(t *testing.T) {
db, mock, _ := sqlmock.New()
models.Db, _ = gorm.Open("postgres", db)
sqlRows := sqlmock.NewRows([]string{"details"}).
AddRow(`{"name": "foo", "type": "bar", ... }`
mock.ExpectQuery("^SELECT (.+) FROM \"products\" (.+)$").WillReturnRows(sqlRows)
...
// some http request recording or other operations
// and then the usual expected := , if ... != t.Errorf combo:
expected := `{"products":[{"details":{"name": "foo", "type": "bar"}}]}` The above assumes that package models
var Db *gorm.DB
...
// somewhere else:
scope := models.Db.Select("id, details, created_at, updated_at")
...
scope.Find(&products) |
Is there an update on the |
I would like to be able to use github.com/stretchr/testify/mock for unit testing my gorm DB instance. However, gorm.DB is a struct and its methods return pointers to the struct. For testify/mock, we need methods to work on interfaces. For instance, gorm.DB.Find must return an interface, not a struct pointer for mocking to work.
What version of Go are you using (
go version
)?go version go1.8.3 darwin/amd64
Which database and its version are you using?
sqlite 3.16.0 2016-11-04 19:09:39 0e5ffd9123d6d2d2b8f3701e8a73cc98a3a7ff5f
What did you do?
Here I have a simple database program that has one model, Item, and one database dependent method. I'd like to unit test
GetItems()
, but I need to mock out the database instance to do that.main.go
main_test.go
The tests run fine and pass, but when I try to run the main file, it fails.
The text was updated successfully, but these errors were encountered: