sqlmock 不匹配查询,但查询相同且日志输出显示相同
在编写使用 Gorm 和 sqlmock 测试代码时遇到一个问题,主要是有关更新函数。
第一个工作流部分仅从数据库中查询记录。即使日志输出显示它们相同,我也无法使其与我的 SQL 匹配。
错误信息如下:
(database.go:263) [2020-01-08 10:29:40] 查询:无法匹配实际 SQL:“SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = ?)) ORDER BY "storage_pools"."id" ASC LIMIT 1” with expected regexp "SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = ?)) ORDER BY "storage_pools"."id" ASC LIMIT 1"
我也尝试使用 ExpectExec 插入 ExpectQuery。
for _, c := range cases { db, mock, err := sqlmock.New() if err != nil { t.Fatal(err) } DB, err := gorm.Open("sqlite3", db) if err != nil { t.Fatal(err) } DB.LogMode(true) mock.ExpectQuery(`SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = ?)) ORDER BY "storage_pools"."id" ASC LIMIT 1`) err = UpdateStoragePool(DB, &c.givenPool) if !reflect.DeepEqual(c.wantedError, err) { t.Fatalf("expecting errror %q, got %q", c.wantedError, err) } // 如果事务期间没有发生任何错误,则检查是否满足所有预期 if c.wantedError == nil { if err := mock.ExpectationsWereMet(); err != nil { t.Fatalf(err.Error()) } } }
我也试过:
mock.ExpectQuery(`SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = '1')) ORDER BY "storage_pools"."id" ASC LIMIT 1`).WithArgs(1) mock.ExpectExec(`SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = ?)) ORDER BY "storage_pools"."id" ASC LIMIT 1`) mock.ExpectExec(`SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = '1')) ORDER BY "storage_pools"."id" ASC LIMIT 1`).WithArgs(1)
这个问题的原因可能有两种可能:
以上是为什么'sqlmock”无法匹配查询,即使查询相同并且日志显示它们相同?的详细内容。更多信息请关注PHP中文网其他相关文章!