I'm practicing testing with Go. I'm building a CRUD operation with Echo and I'm in the state of testing my service.go file. It uses a repository that is a gorm.DB which is connected to my local Postgresql.
Also, previously I tested a Create function in this service file using a similar set-up and it worked as intended! With the GetOne function, however, returns this error:
Previously, I tested the Create function, which works with similar set-ups.
Could anyone guide me on how to correctly mock the return value with go-sqlmock and gorm?
repository.go
func (r *repo) GetByID(id int) (models.Entry, error) {
var entry models.Entry
err := r.Db.Table("entries").First(&entry, id).Error
if err != nil {
return models.Entry{}, err
}
return entry, nil
}
The service.go file
func (s *service) GetOne(id int) (models.Entry, int, error) {
entry, err := s.entryRepo.GetByID(id)
if err != nil {
return models.Entry{}, http.StatusNotFound, err
}
return entry, http.StatusOK, err
}
Here is my service_test.go file
func Test_GetOne(t *testing.T) {
mockDb, mock, err := sqlmock.New()
if err != nil {
t.Error("Failed to create mock database", err.Error())
}
defer mockDb.Close()
dialector := postgres.New(postgres.Config{
Conn: mockDb,
DriverName: "postgres",
})
db, _ := gorm.Open(dialector, &gorm.Config{})
t.Run("Should successfully get an entry", func(t *testing.T) {
rows := sqlmock.NewRows([]string{"all the keys"}).AddRow("all the values")
mock.ExpectBegin()
mock.ExpectQuery("SELECT").WithArgs(1).WillReturnRows(rows)
mock.ExpectCommit()
serv := InitService(db)
entry, status, err := serv.GetOne(1)
if err := mock.ExpectationsWereMet(); err != nil {
t.Error("SQL expressions were not met", err.Error())
}
})
}