I am trying to mock my query functions using go-sqlmock & replicate the database table similarly. However, I am not getting the results that I expect. The query is not behaving as it should, arguments are not being inserted into the query & the actual result is incorrect. What am I doing wrong here?
This is the function & the query I am mocking:
func (y *YumDatabase) getTransactionId(pkg string) (int, error) {
var id int
queryForTid := "SELECT tid FROM trans_cmdline WHERE cmdline LIKE '%install " + pkg + "%' ORDER BY tid DESC LIMIT 1"
row := y.db.QueryRow(queryForTid)
switch err := row.Scan(&id); err {
case sql.ErrNoRows:
fmt.Println("No rows were returned")
return 0, err
case nil:
return id, nil
default:
return 0, err
}
}
And this is the mock test function:
func TestGetTransactionId(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("err not expected: %v", err)
}
pkg := "tcpdump"
rows := sqlmock.NewRows([]string{"tid"}).AddRow("1").AddRow("3")
mock.ExpectQuery("SELECT tid FROM trans_cmdline WHERE cmdline LIKE '%install " + pkg + "%' ORDER BY tid DESC LIMIT 1").WillReturnRows(rows)
mockdb := &YumDatabase{
db: db,
}
got, err := mockdb.getTransactionId("tcpdump")
assert.Equal(t, 3, got)
}
If the above worked as expected, I would get back '3' in 'got' but instead I get back '1'
Secondly, is it possible to change Rows to the following:
rows := sqlmock.NewRows([]string{"tid", "cmdline"}).AddRow("1", "install test").AddRow("3", "delete test2")
And actually do the comparison "WHERE cmdline LIKE '%install XYZ%'", because I tried this and I got back the following error (all of the main code builds & works including the queries, so this is an issue with the mock code I've wrote I'm guessing):
error sql: expected 2 destination arguments in Scan, not 1
I expect to see the highest tid returned from the SQL query, not the first one specified in "AddRow", and I expect the query to implement a check of the "cmdline" row from the mocks.