h2non / gock

HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽
https://pkg.go.dev/github.com/h2non/gock
MIT License
2.09k stars 107 forks source link

gock: cannot match any request In more one http request #48

Closed z2665 closed 5 years ago

z2665 commented 5 years ago

I have a code. It can work before 1.0.14. but in 1.0.14. It can't work

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"

    "gopkg.in/h2non/gock.v1"
)

func main() {
    data := `{"code":0,"msg":"ok"}`
    gock.New("http://big.tree.com").
        MatchParams(map[string]string{
            "moduleName": "MySQL",
        }).
        Reply(200).
        BodyString(data)
    defer gock.Off()
    resp, err := http.Get("http://big.tree.com?moduleName=MySQL")
    defer resp.Body.Close()
    if err != nil {
        panic(err)
    }
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(body))
    resp2, err := http.Get("http://big.tree.com?moduleName=MySQL")
    if err != nil {
        panic(err)
    }
    body, err = ioutil.ReadAll(resp2.Body)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(body))
}

the result is

{"code":0,"msg":"ok"}
panic: Get http://big.tree.com?moduleName=MySQL: gock: cannot match any request

goroutine 1 [running]:
main.main()
        F:/newbr/t1/main.go:32 +0x502
MarkusFreitag commented 5 years ago

The mocked requests is only reachable once, by default. So if you want to use it multiple times, you can either specify the exact number using Times(2) or make it persistent Persist().

gock.New("http://big.tree.com").
    MatchParams(map[string]string{
    "moduleName": "MySQL",
    }).
    Persist().
    Reply(200).
    BodyString(data)
z2665 commented 5 years ago

Thanks, I can use Persist to keep the same behavior likes before version.