Skip to content

Instantly share code, notes, and snippets.

@karlseguin
Created March 10, 2013 12:51
Show Gist options
  • Save karlseguin/5128461 to your computer and use it in GitHub Desktop.
Save karlseguin/5128461 to your computer and use it in GitHub Desktop.
A fake http.ResponseWriter class, used for testing. See http://openmymind.net/Testing-In-Go/
package fakeresponse
import (
"testing"
"net/http"
)
type FakeResponse struct {
t *testing.T
headers http.Header
body []byte
status int
}
func New(t *testing.T) (*FakeResponse) {
return &FakeResponse {
t: t,
headers: make(http.Header),
}
}
func (r *FakeResponse) Header() http.Header {
return r.headers
}
func (r *FakeResponse) Write(body []byte) (int, error) {
r.body = body
return len(body), nil
}
func (r *FakeResponse) WriteHeader(status int) {
r.status = status
}
func (r *FakeResponse) Assert(status int, body string) {
if r.status != status {
r.t.Errorf("expected status %+v to equal %+v", r.status, status)
}
if string(r.body) != body {
r.t.Errorf("expected body %+v to equal %+v", string(r.body), body)
}
}
@karl-gustav
Copy link

karl-gustav commented Jan 25, 2019

Now you can just use the built in ResponseRecorder?

r := httptest.NewRequest("GET", "/foo", nil)
w := httptest.NewRecorder()
handler(w, r)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment