为了账号安全,请及时绑定邮箱和手机立即绑定

SQLMock and Gorm: Mocking Postgres Insert

SQLMock and Gorm: Mocking Postgres Insert

Go
慕村9548890 2022-08-24 20:29:57
当我尝试使用SQLMock模拟Postgres插入并 Gorm.io 时,我收到一个错误,指出查询不是预期的。我试图用它来包装和转义我的字符串,但它不起作用。我添加并删除了参数和结果,但错误继续出现regexp.QuoteMeta()如何通过 SQLMock 设置预期的查询?我给你原始的PostgresQuery和UserModel//RAW QUERYINSERT INTO "users" ("id","name","surname","birthdate","company","custom_claims","deleted") VALUES ($1,$2,$3,$4,$5,$6,$7)' with args [{Name: Ordinal:1 Value:my_user_id} {Name: Ordinal:2 Value:<nil>} {Name: Ordinal:3 Value:<nil>} {Name: Ordinal:4 Value:<nil>} {Name: Ordinal:5 Value:<nil>} {Name: Ordinal:6 Value:<nil>} {Name: Ordinal:7 Value:<nil>}]//Gorm modeltype User struct {    ID           string `gorm:"primaryKey"`    Name         *string    Surname      *string    Birthdate    *time.Time    Company      *string    CustomClaims *json.RawMessage    Deleted      gorm.DeletedAt}func (repository Repository) CreateUser(user users.User) (*users.User, error) {    newUser := toRepositoryModel(user)    err := repository.db.Create(newUser).Error //db -> *gorm.DB    //....}//TESTconst expectedQuery = `INSERT INTO "users" ("id","name","surname","birthdate","company","custom_claims","deleted") VALUES ($1,$2,$3,$4,$5,$6,$7)' with args [{Name: Ordinal:1 Value:my_user_id} {Name: Ordinal:2 Value:<nil>} {Name: Ordinal:3 Value:<nil>} {Name: Ordinal:4 Value:<nil>} {Name: Ordinal:5 Value:<nil>} {Name: Ordinal:6 Value:<nil>} {Name: Ordinal:7 Value:<nil>}]`suite.mock.ExpectQuery(regexp.QuoteMeta(experctedQuery)) //HOW SHOULD BE MODIFIED?user, err2 := postgres.CreateUser(users.User{   ID: ID,})
查看完整描述

1 回答

?
largeQ

TA贡献2039条经验 获得超7个赞

我已经让它工作了。


suite.mock.ExpectExec(regexp.QuoteMeta(`INSERT INTO "users" ("id","name","surname","birthdate","company","custom_claims","deleted") VALUES ($1,$2,$3,$4,$5,$6,$7)`)).WithArgs(ID, nil, nil, nil, nil, nil, nil).WillReturnResult(sqlmock.NewResult(0, 1))

更新


Postgres SELECT :


//Simulate returned row(s)

userMockRows := sqlmock.NewRows([]string{"id", "name", "surname", "birthdate", "company", "custom_claims", "deleted"}).AddRow(ID, nil, nil, nil, nil, nil, nil)


//Expect SELECT

suite.mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "users" WHERE id = $1`)).WithArgs(ID).WillReturnRows(userMockRows)

Postgres UPDATE:


suite.mock.ExpectExec(regexp.QuoteMeta(`UPDATE "users" SET "name"=$1,"surname"=$2,"birthdate"=$3,"company"=$4,"custom_claims"=$5,"deleted"=$6 WHERE "id" = $7`)).WithArgs(newName, nil, nil, nil, nil, nil, ID).WillReturnResult(sqlmock.NewResult(0, 1))


查看完整回答
反对 回复 2022-08-24
  • 1 回答
  • 0 关注
  • 95 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信