h2non / gock

HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽

Home Page:https://pkg.go.dev/github.com/h2non/gock

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Allow specify url.Values as query paramenter

allevo opened this issue · comments

Hi,
thanks for this amazing project!

I've a function like this

func MakeRequest() {
  query := url.Values{}
  query.Add("key1", "value1")
  query.Add("key2", "value2")
  queryString := query.Encode()
  requestURL := fmt.SPrintf("%s?%s, "http://foo.com/bar", queryString)
  res, err := http.Get(requestURL)
  ....
}

I would like to test it. The simplest way to to that is

func Test(t *testing.T) {
  gock.New("http://foo.com").
    Get("/bar").
    MatchParam("key1", "value1").
    MatchParam("key2", "value2").
    Reply(200).
    JSON(map[string]string{"foo": "bar"})
}

Anyway:

  1. this can be a little verbose when the query parameters are a lot
  2. the check is not made against an exactly value

I would like to write something like that:

func Test(t *testing.T) {
  query, err := url.ParseQuery("key1=value1&key2=value2")
  gock.New("http://foo.com").
    Get("/bar").
    MatchExactParamValue(query).
    Reply(200).
    JSON(map[string]string{"foo": "bar"})
}

The check is made exactly using url.Values struct.

Another proposal can be

func Test(t *testing.T) {
  gock.New("http://foo.com").
    Get("/bar").
    MatchParam("key1", "value1").
    MatchParam("key2", "value2").
    MatchParamExactly().
    Reply(200).
    JSON(map[string]string{"foo": "bar"})
}

If you are interested in, I'll send a PR for that implementation or a similar one

commented

That would be nice but I want to be conservative when adding domain-specific API methods for special cases. Right now you can use the AddMatcher(MatchFunc) method for ad-hoc specific matching.

Hi, I don't understand why you consider this change as domain-specific: from developer point of view, I would like to check which parameters are sent to an endpoint