1. 项目地址:
    https://github.com/bouk/monkey

  2. 示例代码:

    1. 项目结构:

      demo
      |-- go.mod
      |-- main.go
      `-- main_test.go
    2. 初始化 go module:
      go mod init demo

    3. main.go

       package main
      
       func Foo(input string) string {
           return input
       }
      
       func Func(input string) string {
           str := Foo(input)
           return str
       }
      
       type Test struct {
           Name string
       }
      
       func (t *Test) A() string {
           return t.Name
       }
      
       func (t *Test) B() string {
           name := t.A()
           return name
       }
    4. main_test.go

       package main
      
       import (
           "bou.ke/monkey"
           "reflect"
           "testing"
       )
      
       func TestFunc(t *testing.T) {
           myStr := "bar"
           // 为函数打桩(自定义函数的返回值)
           monkey.Patch(Foo, func(input string) string {
               return myStr
           })
           retStr := Func("foo")
           if retStr != myStr {
               t.Error("打桩失败!")
           } else {
               t.Log("打桩成功!")
           }
       }
      
       func TestMethod(t *testing.T) {
           myStr := "bar"
           obj := &Test{
               Name: "foo",
           }
           // 为类中的方法打桩(自定义方法的返回值)
           monkey.PatchInstanceMethod(reflect.TypeOf(obj), "A", func(test *Test) string {
               return myStr
           })
           retStr := obj.B()
           if retStr != myStr {
               t.Error("打桩失败!")
           } else {
               t.Log("打桩成功!")
           }
       }
  3. 运行测试命令:

    # 运行指定实例
    go test -v -gcflags=-l -run=Func
    # 运行所有实例
    go test -v -gcflags=-l
文档更新时间: 2024-03-24 15:25   作者:lee