Go sqlmock 测试 MySQL 批量插入

huangapple go评论98阅读模式
英文:

Go sqlmock test MySQL batch insert

问题

我正在使用GORM将多行数据批量插入到MySQL表中,并且我想使用sqlmock来测试其行为是否正确。关于使用sqlmock模拟批量插入的内容,我在网上没有找到相关的信息。

对于插入单行数据,我们可以使用类似以下的代码:

mock.ExpectExec("INSERT INTO product_viewers").WithArgs(2, 3).WillReturnResult(sqlmock.NewResult(1, 1))

但是,对于表示批量插入的多行数据,应该如何传递给ExpectExecWithArgs方法呢?

mock.ExpectExec("INSERT INTO product_viewers").WithArgs(???).WillReturnResult(sqlmock.NewResult(*numInsertedRows*, *numInsertedRows*))

请注意,这里的???表示需要替换为实际的多行数据。

英文:

I am using GORM to batch insert multiple rows into a MySQL table and I want to test that the behaviour is the correct one using sqlmock. I haven't found anything online regarding mocking batch inserts with sqlmock.

For inserting a single row, we would have something similar to:

mock.ExpectExec("INSERT INTO product_viewers").WithArgs(2, 3).WillReturnResult(sqlmock.NewResult(1, 1))

But how should multiple rows' values be passed to ExpectExec in order to represent a batch insert?

mock.ExpectExec("INSERT INTO product_viewers").WithArgs(???).WillReturnResult(sqlmock.NewResult(*numInsertedRows*, *numInsertedRows*))

答案1

得分: 1

答案是,至少对于MySQL来说,sqlmock在不同的行和列之间没有区别,所以你可以在.WithArgs中按顺序逗号分隔地列出所有行的所有值。

例如:

mock.ExpectExec("INSERT INTO product_viewers").
  WithArgs(row1col1, row1col2, row2col1, row2col2, ...).
  WillReturnResult(sqlmock.NewResult(<numInsertedRows>, <numInsertedRows>))
英文:

The answer is, at least for MySQL, that sqlmock doesn't make a difference between different rows and columns, so you can just list all the values from all the rows, one after the other, comma separated, in .WithArgs.

e.g.

mock.ExpectExec(&quot;INSERT INTO product_viewers&quot;).
  WithArgs(row1col1, row1col2, row2col1, row2col2, ...).
  WillReturnResult(sqlmock.NewResult(&lt;numInsertedRows&gt;, &lt;numInsertedRows&gt;))

huangapple
  • 本文由 发表于 2021年8月3日 19:57:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/68635607.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定