首页 > 其他分享 >gomonkey不生效

gomonkey不生效

时间:2023-02-04 20:55:18浏览次数:32  
标签:get res test 生效 go gomonkey mock

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

相关文章