如何设置HTTP GET假响应

时间:2019-12-21 08:41:34

标签: unit-testing http go mocking

给出一个在Go中进行HTTP GET的函数:

package main

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

func CallExample() {
  resp, _ := http.Get("http://example.com/foo")
  body, _ := ioutil.ReadAll(resp.Body)
  return body
}

如何设置一个调用此函数(CallExample)的测试,同时避免发出实际的HTTP GET请求?

package main

import (
  "testing"
)

func TestCallExample(t *testing.T) {
  // What setup do I need here to fake a response from http://example.com/foo?
  got := CallExample()
  want := "foo"
  if got != want {
    t.Errorf("Got %s, Want %s", got, want)
  }
}

我知道这里有一个import "net/http/httptest"库,但尚不清楚如何使用它来拦截GET和伪造响应。可以使用httptest.NewRecorder()进行设置吗?如果您能显示一个示例,其中您伪造了200/404/500状态代码和不同的响应主体,也将不胜感激。谢谢。

解决方案:

必须修改CallExample以接受url的{​​{1}}的{​​{1}}。

httptest.NewServer()

0 个答案:

没有答案