gin
类似
testify's HTTPBodyContain
我很难创造
gin.Context
从
*http.Request
和
*httptest.ResponseRecorder
. 我已经写过这样的东西了:
func HTTPBodyContains(t *testing.T, handler gin.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool {
body := HTTPBody(handler, method, url, values)
contains := strings.Contains(body, fmt.Sprint(str))
if !contains {
assert.Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body))
}
return contains
}
func HTTPBody(handler gin.HandlerFunc, method, url string, values url.Values) string {
w := httptest.NewRecorder()
req, err := http.NewRequest(method, url+"?"+values.Encode(), nil)
if err != nil {
return ""
}
handler(&gin.Context{
Request: req,
Writer: gin.ResponseWriter(w),
})
return w.Body.String()
}
但这不管用
Writer: gin.ResponseWriter(w)