使用 gosqlmock 测试 gorm 问题,将查询与mock.ExpectQuery 和 regexp.QuoteMeta 进行比较

使用 go-sqlmock 测试 gorm 问题,将查询与mock.expectquery 和 regexp.quotemeta 进行比较

在开发过程中,使用 go-sqlmock 来测试 gorm 的问题是一种常见的需求。go-sqlmock 是一个用于模拟数据库操作的工具,而 gorm 则是一个流行的 Go 语言 ORM 库。在测试过程中,我们经常需要比较查询语句是否符合预期。为了做到这一点,我们可以使用 mock.ExpectQuery 和 regexp.QuoteMeta 来进行比较。这种方法能够帮助我们更好地测试和调试代码,确保程序的正确性和稳定性。接下来,我们将详细介绍如何使用 go-sqlmock 进行 gorm 测试,并展示如何使用 mock.ExpectQuery 和 regexp.QuoteMeta 进行查询语句的比较。

问题内容

我在比较预期查询与 gorm 的真实查询时遇到问题,这是我的代码:

package repository import ( "regexp" "testing" "github.com/data-dog/go-sqlmock" "your_go_root/pkg/domain" "github.com/stretchr/testify/assert" "gorm.io/driver/mysql" "gorm.io/gorm" ) var successgettransaction domain.transaction = domain.transaction{ id: 2, buyerid: 2, sellerid: 5, itemid: 2, messageid: 2, expireddate: "2022-09-010 01:01:00", createdat: "2022-09-08 01:01:00", } func testsuccessgettransactionbyid(t *testing.t) { db, mock, err := sqlmock.new() assert.noerror(t, err) gdb, err := gorm.open(mysql.new(mysql.config{ conn: db, skipinitializewithversion: true, }), &gorm.config{}) assert.noerror(t, err) rows := sqlmock.newrows([]string{"id", "buyer_id", "seller_id", "item_id", "message_id", "expired_date", "created_at"}). addrow(2, 2, 5, 2, 2, "2022-09-010 01:01:00", "2022-09-08 01:01:00") mock.expectquery(regexp.quotemeta("select * from transaction where id = ?;")).willreturnrows(rows) repo := defaultclient(gdb) actualsectionlist, _ := repo.gettransactionbyid(2) assert.equal(t, successgettransaction, actualsectionlist, "ambas listas deberian ser iguales") assert.noerror(t, mock.expectationsweremet()) }登录后复制