linzhengen / tech-notes

My tech notes write in github issues🧲
1 stars 0 forks source link

[20210909] golangのHTTP mocking `gock`はいいね #142

Open linzhengen opened 3 years ago

linzhengen commented 3 years ago

GitHub

https://github.com/h2non/gock/

サンプル

package test

import (
  "github.com/nbio/st"
  "gopkg.in/h2non/gock.v1"
  "io/ioutil"
  "net/http"
  "testing"
)

func TestSimple(t *testing.T) {
  defer gock.Off()

  gock.New("http://foo.com").
    Get("/bar").
    Reply(200).
    JSON(map[string]string{"foo": "bar"})

  res, err := http.Get("http://foo.com/bar")
  st.Expect(t, err, nil)
  st.Expect(t, res.StatusCode, 200)

  body, _ := ioutil.ReadAll(res.Body)
  st.Expect(t, string(body)[:13], `{"foo":"bar"}`)

  // Verify that we don't have pending mocks
  st.Expect(t, gock.IsDone(), true)
}

import ( "github.com/nbio/st" "gopkg.in/h2non/gock.v1" "io/ioutil" "net/http" "testing" )

func TestClient(t *testing.T) { defer gock.Off()

gock.New("http://foo.com"). Reply(200). BodyString("foo foo")

req, err := http.NewRequest("GET", "http://foo.com", nil) client := &http.Client{Transport: &http.Transport{}} gock.InterceptClient(client)

res, err := client.Do(req) st.Expect(t, err, nil) st.Expect(t, res.StatusCode, 200) body, _ := ioutil.ReadAll(res.Body) st.Expect(t, string(body), "foo foo")

// Verify that we don't have pending mocks st.Expect(t, gock.IsDone(), true) }