大家好,今天本人给大家带来文章《测试服务器上Oauth2.0资源的方法》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!
我想编写测试代码以验证正确的文档是否可以到达第三方服务器的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 {
...
}
}正确答案
您可以依赖第三方库来模拟资源。您可以查看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())
}
}到这里,我们也就讲完了《测试服务器上Oauth2.0资源的方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
