要模拟方法调用,您需要模拟您的结构。
对于您提供的代码示例,我建议创建一个
Performer实现您的
Perform调用的接口。您的实际结构和模拟结构都将实现此接口。
我也建议您将结构作为参数传递给invoke函数,而不要使用全局变量。
这是一个例子:
type Performer interface { perform()}type A struct {}func (a *A) perform() { fmt.Println("real method")}type AMock struct {}func (a *AMock) perform () { fmt.Println("mocked method")}func caller(p Performer) { p.perform()}在测试中,将模拟插入到您的
invoke呼叫中。在您的真实代码中,将真实结构注入您的
invoke调用中。
使用https://godoc.org/github.com/stretchr/testify/mock之类的库,您甚至可以真正轻松地验证使用正确的参数,正确的次数调用您的方法,并控制模拟的行为。



