gomonkey作用
在运行时把原函数地址替换为目标函数地址
go.mod
require github.com/agiledragon/gomonkey/v2 v2.3.0
a.go
package main
type A struct {}
func (a A) get() int {
return 1
}
mock_test.go
package main
import (
"github.com/agiledragon/gomonkey/v2"
"testing"
)
func Test(t *testing.T) {
patch1 := gomonkey.ApplyFunc(A.get, func(a A) int {
return -1
})
defer patch1.Reset()
var a A
res := a.get()
if res != -1 {
t.Errorf("failed, res is %d", res)
}
}
运行go test -v a.go mock_test.go失败
gomonkey没有生效的原因是,执行成员方法时编译器进行了内联优化,可通过-gcflags=all=-l来取消优化。
运行go test -gcflags=all=-l -v a.go mock_test.go成功
标签:get,res,test,生效,go,gomonkey,mock From: https://www.cnblogs.com/WJQ2017/p/17092365.html