S
S
SSSSTTTTAAAASSSS2021-11-24 16:18:38
go
SSSSTTTTAAAASSSS, 2021-11-24 16:18:38

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
}


Accordingly, the code that should add an entry to the database is as follows:
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()

Already tried and changing mock.ExpectExec to mock.ExpectQuerry didn't help. The result was this
mockedRow := sqlmock.NewRows([]string{"userID", "name", "age"}).AddRow("00000000-0000-0000-0000-000000000000", "name1", 10)

Removed regexp.QuoteMeta, Inserted the full command as in the working code - nothing helps.
I understand that somewhere here I have an error in this description of the mock, but I can’t understand where. Begin and Commit removed nothing helps.
I do not understand where to dig ...
I would be grateful for any hint.
Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kvaks, 2021-11-25
@SSSSTTTTAAAASSSS

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 question

Ask a Question

731 491 924 answers to any question