您可以创建和使用
http.Request伪造的伪造品,在读取其主体时会故意返回错误。您不一定需要一个全新的请求,有缺陷的主体就足够了(这是一个
io.ReadCloser)。
使用此
httptest.NewRequest()函数可以实现最简单的方法,在该函数中您可以传递
io.Reader将用作
io.ReadCloser请求正文的值(包装为)。
这是一个示例
io.Reader,尝试从中读取错误时故意返回错误:
type errReader intfunc (errReader) Read(p []byte) (n int, err error) { return 0, errors.New("test error")}涵盖您的错误情况的示例:
func HandlePostRequest(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() body, err := ioutil.ReadAll(r.Body) if err != nil { fmt.Printf("Error reading the body: %vn", err) return } fmt.Printf("No error, body: %sn", body)}func main() { testRequest := httptest.NewRequest(http.MethodPost, "/something", errReader(0)) HandlePostRequest(nil, testRequest)}输出(在Go Playground上尝试):
Error reading the body: test error



