英文:
Mocking a select with mapping in Go is returning expected transaction begin error
问题
我正在尝试使用go-sqlmock进行简单的单元测试,以执行选择操作并返回映射的ID。以下是代码片段:
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()
我想要测试的实现片段如下:
...
type Project struct{ Id int64 }
var project Project
tx.Raw("select id from project where id = ? and archived = 1", values["projectId"]).Scan(&project)
...
但是出现了以下错误:
我尝试了一些示例,但没有成功。感谢大家的帮助。
更新
我尝试删除代码中的s.sqlmock.ExpectBegin()
和s.sqlmock.ExpectCommit()
,并将查询更改如下:
s.sqlmock.
ExpectQuery("select id from project where id = ? and archived = 1").
WithArgs(2).
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(strconv.Itoa(1)))
但是出现了以下错误:
查询:无法匹配实际的SQL:"select id from project where id = ? and archived = 1"与预期的正则表达式"select id from project where id = ? and archived = 1"。
英文:
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"
答案1
得分: 1
好的,以下是翻译好的内容:
很好,用户的回应 @mh-cbon 运行得很完美。我将默认的匹配器替换为全大写敏感的匹配器,测试通过了!
之前的代码:
var sqlDB *sql.DB
sqlDB, s.sqlmock, _ = sqlmock.New()
s.db, _ = gorm.Open("mysql", sqlDB)
之后的代码:
var sqlDB *sql.DB
sqlDB, s.sqlmock, _ = sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
s.db, _ = gorm.Open("mysql", sqlDB)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论