agiledragon / gomonkey

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

无法mock http.Client的Do方法 #28

Closed XiangZei closed 4 years ago

XiangZei commented 4 years ago

您好,在业务中需要对http请求进行mock,所以对http.Client的Do方法进行打桩,但是用如下的代码打桩之后,发现在实际的使用中并没有生效。想请大神帮忙看看为什么

// http请求打桩
        var c *http.Client
        patches := gomonkey.ApplyMethod(reflect.TypeOf(c), "Do",func(c *http.Client, req *http.Request) (*http.Response, error){
            rsp := &http.Response{}
            if strings.HasPrefix(req.URL.Path, "/fcgi-bin/zx_get_seqno.fcgi") {
                rsp.Body = ioutil.NopCloser(bytes.NewBuffer([]byte(`{"retcode":"0","retmsg`)))
            } else if strings.HasPrefix(req.URL.Path, "/fcgi-bin/zx_put_file.fcgi") {
                rsp.Body = ioutil.NopCloser(bytes.NewBuffer([]byte(`{"retcode":"0","r`)))
            } else if strings.HasPrefix(req.URL.Path, "/fcgi-bin/zx_sm_recognition.fcgi") {
                rsp.Body = ioutil.NopCloser(bytes.NewBuffer([]byte(`{"retcode":"0","r`)))
            } else {
                return nil, nil
            }
            return rsp, nil
        })
        defer patches.Reset()
agiledragon commented 4 years ago

func (c Client) Do(req Request) (*Response, error) { return c.do(req) } 这个函数是内联函数,请参考README中Notes第一条:关闭内联函数