0

I want to code the test for validate the right document to reach to the Oauth2.0 of third party server, how should i complete the pseudocode?

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 {
        ...
    }
}
ccd
  • 5,788
  • 10
  • 46
  • 96

2 Answers2

1

You can rely on a third party library to mock the resource. You can take a look at 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())
    }
}
Samuel Vaillant
  • 3,667
  • 1
  • 14
  • 21
0

Finally i use the normal http client to resolve this problem.

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 {
        ...
    }
}
ccd
  • 5,788
  • 10
  • 46
  • 96