Reputation: 24140
I would like to create a test helper for gin similar to testify's HTTPBodyContain.
I am having a hard time creating gin.Context
from *http.Request
and *httptest.ResponseRecorder
. I've already written something like this:
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()
}
but this wouldn't work
Writer: gin.ResponseWriter(w)
Upvotes: 1
Views: 3480
Reputation: 24140
Ok, so it seems there is CreateTestContext that does what I was looking for.
func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine)
CreateTestContext returns a fresh engine and context for testing purposes
Upvotes: 1