Testing simple web server
Testing web server 101
Testing web server in Golang
create a file with name
<anything>_test.go, these files are ignore by compilerwrite 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 hit
nil, // 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
To verify
Full code server.go
Full code main_test.go
Last updated
Was this helpful?