Answer the question
In order to leave comments, you need to log in
INSERT INTO when testing via sqlmock?
Good day to all!
I write unit tests for my API. For postgreSQL testing, I use the "github.com/DATA-DOG/go-sqlmock" library.
With SELECT queues, everything works, everything is tested, everything is ok.
And with the INSERT command, nothing happens. Gives an error and all.
The method I'm trying to test creates an entry in the database.
func (pdb *PostgresDB) CreateUser(u models.User) (models.User, error) {
pdb.mu.Lock()
defer pdb.mu.Unlock()
id := uuid.New()
idStr := id.String()
_, err := pdb.Pdb.Exec(
`INSERT INTO users (userID, name, age) VALUES ($1, $2, $3)`, idStr, u.Name, u.Age)
if err != nil {
return models.User{}, errors.New("couldn't create user in database")
}
u.ID = idStr
return u, nil
}
mock.ExpectBegin()
mock.ExpectExec(regexp.QuoteMeta(`INSERT INTO users`)).
WithArgs("00000000-0000-0000-0000-000000000000", "name1", 10).
WillReturnResult(sqlmock.NewResult(1, 1))
//mock.ExpectQuery(regexp.QuoteMeta(`INSERT INTO "users" \(userID, name, age\) VALUES \(\$1, \$2, \$3\)`)).
// WithArgs("00000000-0000-0000-0000-000000000000", "name1", 10).
// WillReturnRows(mockedRow)
mock.ExpectCommit()
mockedRow := sqlmock.NewRows([]string{"userID", "name", "age"}).AddRow("00000000-0000-0000-0000-000000000000", "name1", 10)
Answer the question
In order to leave comments, you need to log in
for INSERT you need to add the result and do not forget to frame SQL queries with a slash in mock ( regex online )
here is a code example
mock.ExpectExec(`INSERT INTO Products \(model, company, price\) values \('\$1', \$2, \$3\)`).
WithArgs(tt.args.model, tt.args.company, tt.args.price).
WillReturnResult(sqlmock.NewResult(1, 1))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question