Home > Software engineering >  Mock sql query Golang
Mock sql query Golang

Time:08-24

I have a function :

    func (db *DBSqlx) GetRefreshToken(oldToken string, tx *sqlx.Tx) (string, error) {
    var refreshToken string

    err := db.TemplateGet(
        tx,
        &refreshToken,
        `query`,
        oldToken,
    )

    if err != nil {
        return "", errors.Wrap(err, "не удалось запросить рефреш токен для указанного токена")
    }

    return refreshToken, err
}

How to write a test for this function with mock response?

DB has type :

    type DBSqlx struct {
    PgConn    *sqlx.DB
    PgConnCtx context.Context
}

I tried to write this code. But I don't understand how to use the package correctly.

db, mock, err := sqlmock.New()
if err != nil {
    t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()

mock.ExpectQuery("query").WillReturnRows()

CodePudding user response:

You could use something like https://github.com/DATA-DOG/go-sqlmock to mock database queries with all kinds of control over responses by the database.

Though it should be noted, that mocking database queries in tests is generally not considered good testing practice because it is most likely testing the actual implementation of your program and not it's behavior.

  • Related