Skip to content

Instantly share code, notes, and snippets.

@nicolascb
Last active August 11, 2022 12:01
Show Gist options
  • Save nicolascb/f1677d22b80af91e31afd6c931ee0065 to your computer and use it in GitHub Desktop.
Save nicolascb/f1677d22b80af91e31afd6c931ee0065 to your computer and use it in GitHub Desktop.
func Test_IsPrimeHandler(t *testing.T) {
handler := setupMux()
type args struct {
req *http.Request
}
tests := []struct {
name string
args func(t *testing.T) args
wantCode int
wantBody string
}{
{
name: "must return http.StatusBadRequest to invalid number",
args: func(*testing.T) args {
req, err := http.NewRequest("GET", "/check-is-prime", nil)
if err != nil {
t.Fatalf("fail to create request: %s", err.Error())
}
q := req.URL.Query()
q.Add("number", "not_number")
req.URL.RawQuery = q.Encode()
return args{
req: req,
}
},
wantCode: http.StatusBadRequest,
wantBody: "invalid number\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tArgs := tt.args(t)
resp := httptest.NewRecorder()
handler.ServeHTTP(resp, tArgs.req)
if resp.Result().StatusCode != tt.wantCode {
t.Fatalf("the status code should be [%d] but received [%d]", resp.Result().StatusCode, tt.wantCode)
}
if resp.Body.String() != tt.wantBody {
t.Fatalf("the response body should be [%s] but received [%s]", resp.Body.String(), tt.wantBody)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment