Skip to content

Instantly share code, notes, and snippets.

@fahmifan
Created July 23, 2019 02:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fahmifan/5787ba8244d3d249dc965c2355f41a22 to your computer and use it in GitHub Desktop.
Save fahmifan/5787ba8244d3d249dc965c2355f41a22 to your computer and use it in GitHub Desktop.
sqlmock for select query with and without regex
// with empty New(), you should use regex `(.+)` and escape the `$` using `\\`
db, mock, _ := sqlmock.New()
mock.ExpectQuery("SELECT (.+) FROM \"ARTICLES\" WHERE \"SLUG\" = \\$1").
WithArgs("foobar").
WillReturnRows(
sqlmock.NewRows(columns).AddRow(
"28e8a227-4ebd-43b8-9631-108392ed2ba8",
"foobar",
"Foobar",
"Body foobar",
time.Now(),
time.Now(),
),
)
// if you not use regex `(.+)` add `sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)` in `New()`
db, mock, _ := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
mock.ExpectQuery(`SELECT * FROM "ARTICLES" WHERE "SLUG" = $1`).
WithArgs("foobar").
WillReturnRows(
sqlmock.NewRows(columns).AddRow(
"28e8a227-4ebd-43b8-9631-108392ed2ba8",
"foobar",
"Foobar",
"Body foobar",
time.Now(),
time.Now(),
),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment