Created
August 11, 2022 12:17
-
-
Save nicolascb/d0ca68cd6951fce74f82a14084597869 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", | |
}, | |
{ | |
name: "must return http.StatusOk and true to prime number (7)", | |
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", "7") | |
req.URL.RawQuery = q.Encode() | |
return args{ | |
req: req, | |
} | |
}, | |
wantCode: http.StatusOK, | |
wantBody: "true", | |
}, | |
{ | |
name: "must return http.StatusOk and false because number (1) is not prime", | |
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", "1") | |
req.URL.RawQuery = q.Encode() | |
return args{ | |
req: req, | |
} | |
}, | |
wantCode: http.StatusOK, | |
wantBody: "false", | |
}, | |
} | |
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