如何模拟getClient?

时间:2018-07-03 09:36:23

标签: unit-testing go

我有一个功能:

func HTTPGet(url string) (*http.Response, error) {
    resp, err := getClient().Get(url)
    return resp, err
}

,getClient函数是:

var defaultClient *http.Client
func getClient() *http.Client {
    if defaultClient == nil {
        defaultClient = &http.Client{
            Timeout:   time.Second * 60,
            Transport: newDefaultTransport(),
        }
    }
    return defaultClient
}

我需要为URL的HTTPGet编写测试用例:“ / catalog / v6 / providers”。

我已经为默认URL编写了测试用例,例如:

func Handler(w http.ResponseWriter, r *http.Request) {
     fmt.Fprintf(w, "Hello, Client")
}
func TestHTTPGet(t *testing.T) {
    ts := httptest.NewServer(http.HandlerFunc(Handler))
    defer ts.Close()
    mockServerURL := ts.URL
    resp, err := HTTPGet(mockServerURL)
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    assertEquals("Hello, Client", fmt.Sprintf("%s", body), t)
}

但是如何为特定的URL编写测试用例。

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式阅读和保存请求的网址:

var receivedURL string
func Handler(w http.ResponseWriter, r *http.Request) {
    receivedURL = r.RequestURI
    fmt.Fprintf(w, "Hello, Client")
}

然后稍后对其进行断言:

func TestHTTPGet(t *testing.T) {
    ts := httptest.NewServer(http.HandlerFunc(Handler))
    defer ts.Close()
    mockServerURL := ts.URL
    url := fmt.Sprintf("%s%s", mockServerURL, '/path/to/test')
    resp, err := HTTPGet(mockServerURL)
    defer resp.Body.Close()
    assertEquals(receivedURL, url, t)
}