bytedance / mockey

a simple and easy-to-use golang mock library
Apache License 2.0
556 stars 22 forks source link

如何 mock不同包下的泛型函数? #48

Closed suguimanLogan closed 8 months ago

suguimanLogan commented 8 months ago

//被mock方法 package function

import ( "encoding/json" )

func cover[T any](content string) (T, error) { var v T err := json.Unmarshal([]byte(content), &v) return v, err }

/执行cover方法 package function

import "fmt"

func ExecuteCover() { t, _ := covermap[string]int fmt.Println(t) }

//设置mock,但是下面无法mock不同包下的泛型函数,不知道是否是 go:linkname写法不对 package main

import ( . "github.com/bytedance/mockey" "gotest-utils/utils/function" _ "unsafe" )

func main() { m := make(map[string]int) m["age"] = 27 build := MockGeneric(cover[map[string]int]).To(func(content string) (map[string]int, error) { return m, nil }).Build() function.ExecuteCover() build.UnPatch() function.ExecuteCover()

} //go:linkname cover gotest-utils/utils/function.cover func cover[T any](content string) (T, error)

suguimanLogan commented 8 months ago

已经解决

suguimanLogan commented 8 months ago

已经解决,改成这样就行

suguimanLogan commented 8 months ago

package main

import ( . "github.com/bytedance/mockey" "gotest-utils/utils/function" "time" _ "unsafe" )

func main() { m := make(map[string]int) m["age"] = 27 build := MockGeneric(cover).To(func(content string) (map[string]int, error) { return m, nil }).Build() // 打印map[age:27] function.ExecuteCover() build.UnPatch() //停顿一下,因为上面解除mock有时候并不及时 time.Sleep(time.Duration(1) * time.Second) //打印map[age:1] function.ExecuteCover()

}

//go:linkname cover gotest-utils/utils/function.cover[map[string]int] func cover(content string) (map[string]int, error)