gomonkey不生效

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成功

posted on 2023-02-04 20:49  王景迁  阅读(1187)  评论(0编辑  收藏  举报

导航