英文:
Go sqlmock test MySQL batch insert
问题
我正在使用GORM将多行数据批量插入到MySQL表中,并且我想使用sqlmock来测试其行为是否正确。关于使用sqlmock模拟批量插入的内容,我在网上没有找到相关的信息。
对于插入单行数据,我们可以使用类似以下的代码:
mock.ExpectExec("INSERT INTO product_viewers").WithArgs(2, 3).WillReturnResult(sqlmock.NewResult(1, 1))
但是,对于表示批量插入的多行数据,应该如何传递给ExpectExec
的WithArgs
方法呢?
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("INSERT INTO product_viewers").
WithArgs(row1col1, row1col2, row2col1, row2col2, ...).
WillReturnResult(sqlmock.NewResult(<numInsertedRows>, <numInsertedRows>))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论