给出一个在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()