更新时间:2022-01-29 03:35:20
要模拟方法调用,您需要对结构进行模拟.
To mock a method call, you need to make a mock of your structure.
对于您提供的代码示例,我建议创建一个实现您的Perform
调用的Performer
接口.您的真实结构和模拟结构都将实现此接口.
With the code example you provided, I would recommend making a Performer
interface that implements your Perform
call. Both your real structure and your mock structure would implement this interface.
我还建议您将结构作为参数传递给invoke函数,而不要使用全局变量.
I would also recommend passing your structure as an argument to the invoke function instead of using a global variable.
这里是一个例子:
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
调用.
In your tests, inject the mock to your invoke
call.
In your real code, inject the real structure to your invoke
call.
使用类似> https://godoc.org/github.com/stretchr的库/testify/mock ,您甚至还可以真正轻松地验证使用正确的参数(正确的次数)调用了您的方法,并控制了模拟的行为.
Using a library like https://godoc.org/github.com/stretchr/testify/mock you will even be able to really easily verify that your method is called with the right arguments, called the right amount of times, and control the mock's behavior.