down_load1117 2017-11-22 13:43
浏览 93
已采纳

如何模拟返回JSON响应的http.Client

I'm trying to test a method that uses net/http to make requests. Specifically what I'm trying to achieve is to inject a mock http.Client that responds with a certain JSON body

type clientMock struct{}

func (c *clientMock) Do(req *http.Request) (*http.Response, error) {
  json := struct {
    AccessToken string `json:"access_token`
    Scope       string `json:"scope"`
  }{
    AccessToken: "123457678",
    Scope:       "read, write",
  }
  body := json.Marshal(json)
  res := &http.Response {
    StatusCode: http.StatusOK,
    Body:       // I haven't got a clue what to put here
  }
  return res
}

func TestRequest(t *testing.T) { //tests here }

I do know that the Body is of a type io.ReadCloser interface. Trouble is I can't for the life of me find a way to implement it in the mock body response.

Examples as found here so far only demonstrates returning a blank &http.Response{}

  • 写回答

3条回答 默认 最新

  • dprnr5559 2017-11-22 13:49
    关注

    While it's probably more useful to mock the full request cycle with httptest.Server, you can use ioutil.NopCloser to create the closer around any reader:

    Body: ioutil.NopCloser(bytes.NewReader(body))
    

    and if you want an empty body, just provider a reader with no content.

    Body: ioutil.NopCloser(bytes.NewReader(nil))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?