How to Test HTTP Calls in Go Using httptest
Introduction
HTTP testing in Go can be facilitated using the httptest package. This article explores how to leverage httptest for response and server testing, including a detailed example of server testing.
Types of Tests
httptest provides two categories of tests:
Response Test
In response testing, a Recorder object captures the response and its contents. The following code snippet demonstrates a response test:
resp := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/3D/header/?", nil) http.DefaultServeMux.ServeHTTP(resp, req)
Server Test
For server testing, httptest simulates a server and provides a URL that can be used:
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, `{"fake twitter json string"}`) }))
In this example, a server that responds with predefined JSON data is created. The URL of this server can then be used in the application under test.
Example: Testing HTTP Calls in retrieveTweets
To test the retrieveTweets function:
func TestIt(t *testing.T){ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, `{"fake twitter json string"}`) })) defer ts.Close() twitterUrl = ts.URL c := make(chan *twitterResult) go retrieveTweets(c) tweet := <-c if tweet != expected1 { t.Fail() } tweet = <-c if tweet != expected2 { t.Fail() } }
By mocking the server, we can verify the results received by the retrieveTweets function.
The above is the detailed content of How to Effectively Test HTTP Calls in Go using `httptest`?. For more information, please follow other related articles on the PHP Chinese website!