#759·sqlx

How to mock QueryerContext interface when it returns a sqlx.Row?

Author: astrieannaCreated Jul 30, 2021Updated Sep 29, 2026

I want to generate mocks for the sqlx interfaces that my code uses with mockgen, so that I can easily write unit tests to exercise error handling in my code.

Generating a QueryerContext mock is easy, but generating a return value for the functions is harder. For example, QueryRowxContext return a Row, which is a struct. I can mock the interface I actually need (Scanner), but I can't make it into a sqlx.Row.

Would it be possible for QueryerContext to return some interface rather than a struct to make this easier?

For context, these are the lines I'm using to generate mocks with gomock:

//go:generate go run github.com/golang/mock/mockgen -destination=sqlx_mocks/QueryerContext.go -package=sqlx_mocks github.com/jmoiron/sqlx QueryerContext
//go:generate go run github.com/golang/mock/mockgen -destination=sqlx_mocks/Scanner.go -package=sqlx_mocks database/sql Scanner

And the code I'm trying to test is essentially:

// repo.db is a sqlx.QueryerContext, query is string
var createdAt sql.NullInt64
err := repo.db.QueryRowxContext(ctx, query).Scan(&createdAt)
if err != nil {
    return err
}

I want to be able to control what Scan returns so that I can reach the code in the if-statement.