0

我想编写测试代码以验证正确的文档以到达第三方服务器的 Oauth2.0,我应该如何完成伪代码?

import (
    "net/http"
    "net/http/httptest"
}

func testAuthServer(t *testing.T) {
    form := url.Values{}
    form.Set(...)

    r := httptest.NewRequest(http.MethodPost, authUrl, strings.NewReader(form.Encode()))
    r.Header.Set("Content-Type", "application/x-www-form-urlencoded")

    w := httptest.NewRecorder()

    // test the auth server

    if w.Code != http.StatusOK {
        ...
    }
}
4

2 回答 2

1

您可以依靠第三方库来模拟资源。你可以看看gock

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

    authURL := "http://third-party-resource.com"
    form := url.Values{}
    form.Add("foo", "bar")

    // Create the mock of the third-party resource. We assert that the code
    // calls the resource with a POST request with the body set to "foo=bar"
    gock.New(authURL).
        Post("/").
        BodyString("foo=bar").
        Reply(200)

    r, err := http.NewRequest(http.MethodPost, authURL, strings.NewReader(form.Encode()))
    if err != nil {
        t.Fatal(err)
    }

    r.Header.Set("Content-Type", "application/x-www-form-urlencoded")

    c := http.Client{}
    _, err = c.Do(r)
    if err != nil {
        t.Fatal(err)
    }

    if !gock.IsDone() {
        // The mock has not been called.
        t.Fatal(gock.GetUnmatchedRequests())
    }
}
于 2021-09-09T10:29:43.947 回答
0

最后我使用普通的http客户端来解决这个问题。

import (
    "net/http"
}

func testAuthServer(t *testing.T) {
    form := url.Values{}
    form.Set(...)

    authReq := http.NewRequest(http.MethodPost, authUrl, strings.NewReader(form.Encode()))
    authReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")

    authClient, _ := http.Client{}
    authResp, _ := authClient.Do(authReq)

    if authResp.Code != http.StatusOK {
        ...
    }
}
于 2021-09-10T01:13:11.860 回答