agiledragon / gomonkey

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

ApplyMethod error occurred, target type and double type are different #110

Closed mmccto1500 closed 2 years ago

mmccto1500 commented 2 years ago

My code:

type sampleStruct struct {
    ctx context.Context
}

func (ss *sampleStruct) Test(a int, b string) error {
    fmt.Println("this is test")
    // ....
    return nil
}

mOne := &sampleStruct{}

patchMethodOne := gomonkey.ApplyMethod(reflect.TypeOf(mOne), "Test",
                    func(a int, b string) error {
    // this is patch part
    return nil
})

defer patchMethodOne.close()

This code will bring out an error which indicates the following content:

panic: target type(func(*sampleStruct, a int, b string) error) and double type(func(a int, b string) error) are different

Is there any idea about this problem?

qiuchengxuan commented 2 years ago

change

patchMethodOne := gomonkey.ApplyMethod(reflect.TypeOf(mOne), "Test",
                    func(a int, b string) error {
    // this is patch part
    return nil
})

to

patchMethodOne := gomonkey.ApplyMethod(reflect.TypeOf(mOne), "Test",
                    func(ss *sampleStruct, a int, b string) error {
    // this is patch part
    return nil
})
mmccto1500 commented 2 years ago

change

patchMethodOne := gomonkey.ApplyMethod(reflect.TypeOf(mOne), "Test",
                    func(a int, b string) error {
    // this is patch part
    return nil
})

to

patchMethodOne := gomonkey.ApplyMethod(reflect.TypeOf(mOne), "Test",
                    func(ss *sampleStruct, a int, b string) error {
    // this is patch part
    return nil
})

Smart chocie! It seems that the "double type" function needs the receiver itself as the first argument. This perfectly solve my problem, thks:)