你可以做以下操作:
在你的 client.go 文件中:
var cl HTTPClient
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
func init() {
cl = &http.Client{}
}
func Start() error {
req, err := http.NewRequest(http.MethodPost, Url, bytes.NewBuffer(jsonData))
if err != nil {
log.Printf("Error in creating new HTTP request: %v", err)
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := cl.Do(req)
if err != nil {
log.Printf("Error in sending HTTP request: %v", err)
return err
}
defer resp.Body.Close()
log.Printf("Successfully sent HTTP request")
return nil
}
在你的client_test.go文件中
const errHttpFake = "fake HTTP Error"
type mockDoType func(req *http.Request) (*http.Response, error)
type mockClient struct {
mockDo mockDoType
}
func (m *mockClient) Do(req *http.Request) (*http.Response, error) {
return m.mockDo(req)
}
func getHttpFailureClient() {
req := io.NopCloser(bytes.NewReader([]byte(mockResult)))
cl = &mockClient{
mockDo: func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 404,
Body: req,
}, errors.New(errHttpFake)
},
}
}
func getHttpSuccessClient() {
req := io.NopCloser(bytes.NewReader([]byte(mockResult)))
cl = &mockClient{
mockDo: func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 200,
Body: req,
}, nil
},
}
}
func TestHttpSuccess(t *testing.T) {
getHttpSuccessClient()
errHttp := Start()
assert.Nil(t, errHttp)
}
func TestHttpClientFailure(t *testing.T) {
getHttpFailureClient()
errHttp := Start()
assert.NotNil(t, errHttp)
}
ioutil.NopCloser(bytes.NewReader(body))
来设置响应的Body
字段。 - mkopriva