我将Gorm与 postgresql 驱动程序一起使用。我尝试使用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)
}
}
不幸的是,这给了我一个错误:
error was not expected: all expectations were already fulfilled, call to database transaction Begin was not expected
如何正确测试带有 gorm、postgresql 和 sql-mock 的插入?