João Manolo
João Manolo

Reputation: 255

Mocking a select with mapping in Go is returning expected transaction begin error

I'm trying to do a simple unit test using go-sqlmock to do a select and return a mapped ID. Code snippet below

    s.sqlmock.ExpectBegin()
    s.sqlmock.
        ExpectQuery("select `id` from `project` where `id` = \\? and `archived` = \\1").
        WithArgs(2).
        WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(strconv.Itoa(1)))
    s.sqlmock.ExpectCommit()

The snippet of the implementation I want to test on is:

...

    type Project struct{ Id int64 }

    var project Project

    tx.Raw("select id from project where id = ? and archived = 1", values["projectId"]).Scan(&project)

...

But the following error occurs:

enter image description here

I've tried some examples but without success. I thank the help of all you

UPDATE


I tried to remove s.sqlmock.ExpectBegin() and s.sqlmock.ExpectCommit() of code and change a query as below:

    s.sqlmock.
        ExpectQuery("select id from project where id = ? and archived = 1").
        WithArgs(2).
        WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(strconv.Itoa(1)))

But the following error occurs:

Query: could not match actual sql: "select id from project where id = ? and archived = 1" with expected regexp "select id from project where id = ? and archived = 1"

Upvotes: 1

Views: 1861

Answers (1)

João Manolo
João Manolo

Reputation: 255

Well, the user response @mh-cbon worked perfectly. I replaced my default matcher for full case sensitive and the test passed!

before:

    var sqlDB *sql.DB

    sqlDB, s.sqlmock, _ = sqlmock.New()
    s.db, _ = gorm.Open("mysql", sqlDB)

after:

    var sqlDB *sql.DB

    sqlDB, s.sqlmock, _ = sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
    s.db, _ = gorm.Open("mysql", sqlDB)

Upvotes: 1

Related Questions