英文:
mocking http poster in test how to take a resp any type to *http.response to set status code
问题
如上所述,
httpPoster := fakeHTTPPoster{
fnPost: func(ctx context.Context, postURL string, req any, resp any) error {
resp.(*http.Response).StatusCode = 200
return nil
},
}
我想将该响应转换为*http.response,以便我可以设置状态码以通过测试,你知道如何解决这个问题吗?
与上述相关的模拟结构和方法是,
type fakeHTTPPoster struct {
fnPost func(ctx context.Context, postURL string, req any, resp any) error
}
func (f fakeHTTPPoster) Post(ctx context.Context, postURL string, req any, resp any) error {
return f.fnPost(ctx, postURL, req, resp)
}
// 上述接口
type HTTPPoster interface {
Post(ctx context.Context, postURL string, req, resp any) error
}
输出结果是,我希望resp.StatusCode=200,这样就不会导致测试失败:restp.StatusCode != 200 {error}
英文:
as above,
httpPoster := fakeHTTPPoster{
fnPost: func(ctx context.Context, postURL string, req any, resp any) error {
resp.(*http.Response).StatusCode = 200
return nil
},
}
Trying to turn that response into *http.response so I can set a status code to allow a test to pass, any clue on how to resolve this?
The struct and method that is a mock relating to the above is,
type fakeHTTPPoster struct {
fnPost func(ctx context.Context, postURL string, req any, resp any) error
}
func (f fakeHTTPPoster) Post(ctx context.Context, postURL string, req any, resp any) error {
return f.fnPost(ctx, postURL, req, resp)
}
//The o.g. interface
type HTTPPoster interface {
Post(ctx context.Context, postURL string, req, resp any) error
}
The output being, i want resp.StatusCode=200, so it won't fail a test of restp.StatusCode !=200{error}
答案1
得分: 2
如果你想在fnpost
中进行真实的HTTP请求,这里是示例代码:
httpPoster := fakeHTTPPoster{
fnPost: func(ctx context.Context, postURL string, req any, resp any) error {
client := http.Client{Timeout: time.Duration(10) * time.Second}
postReq, ok := req.(*http.Request)
if !ok {
return fmt.Errorf("无效的HTTP请求")
}
postReq.URL.RawPath = postURL
resp, err := client.Do(postReq)
if err != nil {
// 忽略错误?
}
resp.(*http.Response).StatusCode = 200
return nil
},
}
英文:
If you want to do a real HTTP request in fnpost
, here is the sample codes
httpPoster := fakeHTTPPoster{
fnPost: func(ctx context.Context, postURL string, req any, resp any) error {
client := http.Client{Timeout: time.Duration(10) * time.Second}
postReq, ok := req.(*http.Request)
if !ok {
return fmt.Errorf("invalid http request")
}
postReq.URL.RawPath = postURL
resp, err := client.Do(postReq)
if err != nil {
// ignore the err ?
}
resp.(*http.Response).StatusCode = 200
return nil
},
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论