go - SQLMock 和 Gorm : Mocking Postgres Insert

标签 go go-gorm go-sqlmock

当我尝试使用 SQLMock 和 Gorm.io 模拟 Postgres 插入时,我收到一条错误,指出该查询不是预期的。我尝试使用 regexp.QuoteMeta() 来换行并转义我的字符串,但它不起作用。我添加并删除了参数和结果,但错误仍然出现

如何通过 SQLMock 设置预期的查询?

我给你原始的 PostgresQuery 和 UserModel

//RAW QUERY
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>}]
//Gorm model
type 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

    //....
}
//TEST
const 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,
})
//ERROR
"call to ExecQuery '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>}], was not expected, next expectation is: ExpectedQuery => expecting Query, QueryContext or QueryRow which:\n  - matches sql: '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>\\}\\]'\n  - is without arguments",
          }
          call to ExecQuery '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>}], was not expected, next expectation is: ExpectedQuery => expecting Query, QueryContext or QueryRow which:
            - matches sql: '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>\}\]'
            - is without arguments
      occurred

最佳答案

我已经成功了。

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 选择:

//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 更新:

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))

关于go - SQLMock 和 Gorm : Mocking Postgres Insert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67345549/

相关文章:

go - gorm创建表失败,没有任何错误

sql - sqlmock:期望值不匹配(完全相同的查询)

unit-testing - 如何使用sqlmock mock db,函数内获取的db连接

go - 当参数为 int 时,为什么会出现编译错误 'cannot use ... as type uint8 in argument to ...'

for-loop - Go中使用 "continue Label"和使用 "break"跳出内循环的区别

postgresql - Gorm 总是返回具有 nil 值的结构

unit-testing - 如何为 BindJSON 设置模拟 gin.Context

go - "unexpected end of JSON input"当在 POST 请求中传递对象数组时

go - 在 golang jwt-go 中解码 JWT

go - 尝试格式化API响应,但我不知道如何