Closed dennisleung closed 2 years ago
想做个能记录mockFn被调用多少次以及每次调用入参的工具函数,源码如下:
type Recorder struct { history [][]reflect.Value m *gomonkey.Patches } func (r *Recorder) Times() int { return len(r.history) } func (r *Recorder) Reset() { r.m.Reset() } func mockAndRecord(target interface{}, method string, fn interface{}) *Recorder { recorder := Recorder{history: [][]reflect.Value{}} recorderFn := reflect.MakeFunc(reflect.TypeOf(fn), func(args []reflect.Value) (results []reflect.Value) { recorder.history = append(recorder.history, args) return reflect.ValueOf(fn).Call(args) }) m := gomonkey.ApplyMethod(reflect.TypeOf(target), method, recorderFn) //这里报错"double is not a func" recorder.m = m return &recorder }
ApplyMethod的第三个参数是通过reflect.MakeFunc动态生成。recorderFn是reflect.Value,recorderFn.Kind()返回func,但是gomonkey调用ApplyCore的时候又调用调用了一次reflect.ValueOf,导致后面check方法判断入参类型为struct。
ApplyMethod
reflect.MakeFunc
recorderFn.Kind()
func
reflect.ValueOf
struct
能否在调用ApplyCore之前判断下,如果double已经是reflect.Value,就不再调用reflect.ValueOf来规避这个问题?
暂不修改,你可以直接调用ApplyCore来规避。 后续会考虑通过DSL来支持相关的扩展功能,让用户轻松拥有定制能力。
想做个能记录mockFn被调用多少次以及每次调用入参的工具函数,源码如下:
ApplyMethod
的第三个参数是通过reflect.MakeFunc
动态生成。recorderFn是reflect.Value,recorderFn.Kind()
返回func
,但是gomonkey调用ApplyCore的时候又调用调用了一次reflect.ValueOf
,导致后面check方法判断入参类型为struct
。能否在调用ApplyCore之前判断下,如果double已经是reflect.Value,就不再调用reflect.ValueOf来规避这个问题?