有一个未匹配的剩余期望:ExpectQuery => 期望 Query、QueryContext 或 QueryRow



我有这个存储库

func (r *WorkspaceRepository) Delete(id any) (bool, error) {
if err := r.db.Delete(&model.Workspace{}, "id = ?", id).Error; err != nil {
return false, err
}
return true, nil
}
软删除,此Delete操作运行的查询是这个

更新"workspaces"SET "deleted_at"='2022-07-04 09:09:20.778' WHERE id =' c4610193-b43a-4ed7-9ed6-9d67b3f97502' AND "为空

我的测试

uid := uuid.New()
mock.ExpectBegin()
mock.ExpectQuery(regexp.QuoteMeta(`UPDATE "workspaces" SET`)).WithArgs(sqlmock.AnyArg(), uid)
mock.ExpectCommit()
_, err = repository.Delete(uid)
assert.NoError(t, err)

我得到了错误

workspace_test.go:165: 
Error Trace:    workspace_test.go:165
Error:          Received unexpected error:
call to ExecQuery 'UPDATE "workspaces" SET "deleted_at"=$1 WHERE id = $2 AND "workspaces"."deleted_at" IS NULL' with args [{Name: Ordinal:1 Value:2022-07-04 10:54:16.4863731 -0300 -03} {Name: Ordinal:2 Value:ae4124d9-ed16-4dcf-beb9-fcdcf27ca7da}], was not expected, next expectation is: ExpectedQuery => expecting Query, QueryContext or QueryRow which:
- matches sql: 'UPDATE "workspaces" SET'
- is with arguments:
0 - {}
1 - ae4124d9-ed16-4dcf-beb9-fcdcf27ca7da; call to Rollback transaction, was not expected, next expectation is: ExpectedQuery => expecting Query, QueryContext or QueryRow which:
- matches sql: 'UPDATE "workspaces" SET'
- is with arguments:
0 - {}
1 - ae4124d9-ed16-4dcf-beb9-fcdcf27ca7da
Test:           TestDeleteWorkspace

我花了一些时间才弄清楚,但是,如果你知道如何读取错误消息,sqlmock错误解释了这个问题。

在我们的代码中,我们执行触发Execdb驱动命令的UPDATE语句,而不是用于选择的Query

错误信息解释了sqlmock期望代码执行以下操作之一:

下一个期望是:ExpectedQuery =>期望查询,QueryContext或QueryRow

我们需要用ExpectExec()代替ExpectQuery()测试来匹配我们的代码。我们还需要通过添加WillReturnResult(sqlmock.NewResult(1, 1))来定义在模拟数据库中有多少条记录是updated

修复一行,测试应该通过:

mock.ExpectExec(regexp.QuoteMeta(`UPDATE "workspaces" SET`)).WithArgs(sqlmock.AnyArg(), uid).WillReturnResult(sqlmock.NewResult(1, 1))

最新更新