我试图找到一个编写测试和模拟HTTP响应的解决方案。在我的函数中,我接受接口:
type HttpClient interface {
Do(req *http.Request) (*http.Response, error)
}我使用基本auth发出http get请求。
func GetOverview(client HttpClient, overview *Overview) (*Overview, error) {
request, err := http.NewRequest("GET", fmt.Sprintf("%s:%s/api/overview", overview.Config.Url, overview.Config.Port), nil)
if (err != nil) {
log.Println(err)
}
request.SetBasicAuth(overview.Config.User, overview.Config.Password)
resp, err := client.Do(request)我怎么能嘲笑这个HttpClient呢?我正在寻找模拟库,例如:https://github.com/h2non/gock,但是只有用于Get和Post的模拟
也许我该换一种方式。我会很感激你的建议
发布于 2017-04-05 20:45:15
任何具有与您在接口中的签名相匹配的方法的结构都将实现该接口。例如,您可以创建一个结构ClientMock。
type ClientMock struct {
}用这种方法
func (c *ClientMock) Do(req *http.Request) (*http.Response, error) {
return &http.Response{}, nil
}然后,您可以将这个ClientMock结构插入到GetOverview功能中。这里是围棋游乐场的一个例子。
发布于 2018-07-07 23:22:09
net/http/httptest包是您最好的朋友:
// generate a test server so we can capture and inspect the request
testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(scenario.expectedRespStatus)
res.Write([]byte("body"))
}))
defer func() { testServer.Close() }()
req, err := http.NewRequest(http.MethodGet, testServer.URL, nil)
assert.NoError(t, err)
res, err := http.DefaultClient.Do(req)
assert.NoError(t, err)
assert.Equal(t, scenario.expectedRespStatus, res.StatusCode, "status code should match the expected response")发布于 2017-04-06 03:31:45
您必须创建一个具有匹配接口的方法的结构。模拟通常用于测试目的,因此人们希望能够准备模拟方法的返回值。为此,我们使用与方法相对应的func属性创建struct。
因为您的界面是:
type HttpClient interface {
Do(req *http.Request) (*http.Response, error)
}等效模拟:
type MockClient struct {
DoFunc func(req *http.Request) (*http.Response, error)
}
func (m *MockClient) Do(req *http.Request) (*http.Response, error) {
if m.DoFunc != nil {
return m.DoFunc(req)
}
return &http.Response{}, nil
}然后,下一步是编写一些测试。例如这里。
https://stackoverflow.com/questions/43240970
复制相似问题