假设我们有一个库提供了一个 Double 函数来将整数加倍,我们使用指针 i 来获取结果值而不是通过返回:
package api
type Action interface {
Double(i *int) error
}
type NUM struct{}
func (n NUM) Double(i *int) error {
*i *= 2
return nil
}
Run Code Online (Sandbox Code Playgroud)
在我们的主函数中,我们使用这个库来完成我们的任务。像这样:
package app
import (
"fmt"
"github.com/hotsnow/api"
)
func main() {
j := job{a: &api.NUM{}}
d := j.task(3)
fmt.Println(3, d)
}
type job struct {
a api.Action
}
// double me
func (j job) task(i int) int {
j.a.Double(&i)
return i
}
Run Code Online (Sandbox Code Playgroud)
现在我们需要测试task()函数,我们怎样才能通过模拟Double函数获得指针返回呢?
这是测试:
package app
import (
"github.com/golang/mock/gomock"
"github.com/hotsnow/mocks"
"testing"
)
func TestReq(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mocks.NewMockAction(ctrl)
m.EXPECT().Double(gomock.Any()).Return(nil)
j := job{a: m}
got := j.task(3)
if got != 6 {
t.Errorf("got = %#v; want 6", got)
}
}
Run Code Online (Sandbox Code Playgroud)
代码在这里: https: //github.com/hotsnow/mock.git(stackoverflow分支)
小智 7
您可以为此使用 gomock setarg函数
yourPackage.EXPECT().insert(&pointer).SetArg(0, newPointer)
Run Code Online (Sandbox Code Playgroud)
看来你不必使用gomock来测试该task方法。
既然你有一个接口,为什么不直接创建该接口的模拟实现,例如:
type dummy struct{
callCount int
}
func (d *dummy) Double(i *int) error {
d.callCount++
return nil
}
d := dummy{}
j := job{a: &d}
got := j.task(3)
if d.callCount != 1 {
// XXX
}
Run Code Online (Sandbox Code Playgroud)