create a file with name <anything>_test.go, these files are ignore by compiler
write a func matching func TestXxx(*testing.T) where Xxx does not start with a lowercase letter. The function name serves to identify the test routine.
To run the test : go test
Testing
inorder to test the handler, we call it by passing http.ResponseWriter and *http.Request
to create a new Request
req, err := http.NewRequest( http.MethodGet, // defining method of HTTP request"http://localhost:8080/", // Url to hitnil, // Body (taking nil right now))// checking for any errors if err !=nil { t.Fatalf("Could not create a request %v", err)}
To record the response from the writer
rec := httptest.NewRecorder()
To verify
// calling the functionhelloWorldEndPoint(rec, req)// checking status codeif rec.Code != http.StatusOK { t.Errorf("accepted status 200, got %v", rec.Code)}// checking the msg returnedif!strings.Contains(rec.Body.String(), "hello world") { t.Errorf("unexpected body in response %q", rec.Body.String())}