agiledragon / gomonkey

gomonkey is a library to make monkey patching in unit tests easy
MIT License
1.93k stars 179 forks source link

使用ApplyMethod替换gin.Context的方法未生效,为何? #22

Open listen-lavender opened 4 years ago

listen-lavender commented 4 years ago
import (
    "reflect"
    "testing"

    "github.com/agiledragon/gomonkey"
    "github.com/gin-gonic/gin"
    "github.com/golang/mock/gomock"
)

func TestSeq_GIN(t *testing.T) {
    ctrl := gomock.NewController(t)
    defer ctrl.Finish()

    ginCtx := &gin.Context{
        Params: gin.Params{
            gin.Param{
                Key:   "ns",
                Value: "aaaa",
            },
        },
    }

    patches := gomonkey.ApplyMethod(reflect.TypeOf(ginCtx), "Param", func(_ *gin.Context, _ string) string {
        return "bbbb"
    })

    defer patches.Reset()

    println("===1", ginCtx.Param("ns"))
    t.Log("===2", ginCtx.Param("ns"))
}

go test -v 输出结果

image

linqh1 commented 4 years ago

加上一个参数: go test -gcflags="all=-N -l"

https://github.com/agiledragon/gomonkey/issues/4#issuecomment-432503656

wingyiu commented 3 years ago

woca