简体   繁体   中英

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:

在此处输入图片说明

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"

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM