我在 Go 中有一个函数,它接受一个输入参数,修改它,最后返回它。具体来说,这个函数使用 Bun ORM 在 DB 中持久化一些数据并返回持久化的实体。也就是说,我有一个单元测试,我在其中模拟了这个函数,并且需要模拟函数返回它作为参数接收的变量。让我们用一个相当简单的例子更好地解释它:
package doer
type Something struct {
Message string
}
type Doer interface {
DoSomething(s *Something) *Something
}
func TestDoer(t *testing.T) {
var response *doer.Something
request := &doer.Something{
Message: "foo",
}
sut := mocks.Doer{}
sut.On("DoSomething", mock.Anything).Run(func(args mock.Arguments) {
response = args.Get(0).(*doer.Something)
}).Return(response)
r := sut.DoSomething(request)
assert.Equal(t, request.Message, r.Message)
}
我在这里面临的问题是断言会引发恐慌,因为
r
是nil
。想了想,我觉得会出现这种情况是因为Return
在传递给Run
的函数之前执行,此时response
是nil
,所以总是返回nil
。也就是说,我想知道是否有任何方法可以实现我想要的。
请考虑到我需要遵守接口,我已经知道我可以只依赖传递给函数的指针作为输入参数并摆脱返回值,但我需要坚持这个约定。
编辑:我使用
testify
作为模拟框架