Skip to content

Instantly share code, notes, and snippets.

@dtext
Created May 8, 2020 12:41
Show Gist options
  • Save dtext/5a98d29437a676e3b1ffc1c7148cde35 to your computer and use it in GitHub Desktop.
Save dtext/5a98d29437a676e3b1ffc1c7148cde35 to your computer and use it in GitHub Desktop.
Go HTTP Handler Test Boilerplate
func Test_Handler(t *testing.T) {
type fields struct {
}
type args struct {
body string
}
type responseType struct{
}
tests := []struct {
name string
fields fields
args args
wantStatusCode int
wantResponse responseType
}{
{
name: "",
fields: fields{},
args: args{
body: "",
},
wantStatusCode: 200,
wantResponse: responseType{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
handler := CreateHandler(
// TODO add fields
)
req := httptest.NewRequest(http.MethodGet, "/resource", strings.NewReader(tt.args.body))
rec := httptest.NewRecorder()
handler(rec, req)
assert.Equal(t, tt.wantStatusCode, rec.Code)
if tt.wantStatusCode/100 == 2 {
var got responseType
_ = json.NewDecoder(rec.Body).Decode(&got)
assert.Equal(t, tt.wantResponse, got)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment