I'm using Gorm with the postgresql driver. I try to mock a database insert with go-sqlmock:
type Test struct {
FirstName string `json:"first_name"`
}
func (db *DB) CreateTest() (*Test, error) {
test := Test{"c"}
if result := db.Create(&test); result.Error != nil {
return nil, result.Error
}
return &test, nil
}
func TestCreateUser(t *testing.T) {
_, mock, _ := sqlmock.NewWithDSN("sqlmock_db_0")
mockedGorm, _ := gorm.Open("sqlmock", "sqlmock_db_0")
defer mockedGorm.Close()
myDB := &DB{mockedGorm}
mock.ExpectExec("INSERT INTO test").WithArgs("c").WillReturnResult(sqlmock.NewResult(1, 1))
myDB.Exec("INSERT INTO test(first_name) VALUES (?)", "c")
if _, err := myDB.CreateTest(); err != nil {
t.Errorf("error was not expected: %s", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
Unfortunately, this gives me an error:
error was not expected: all expectations were already fulfilled, call to database transaction Begin was not expected
How do I test an insert with gorm, postgresql and sql-mock properly?
You need to call mock.ExpectBegin() before updates and inserts
RépondreSupprimerAlso I'm not sure if you'll run into this since you're using the sqlmock driver, but you should take note of this issue https://github.com/DATA-DOG/go-sqlmock/issues/118#issuecomment-450974462