Last active
October 29, 2019 22:25
-
-
Save efueyo/469576e9b416cf28736abbc4af80e2ac to your computer and use it in GitHub Desktop.
httptest.Server example
This file contains 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
package main_test | |
import ( | |
"fmt" | |
"net/http" | |
"net/http/httptest" | |
"testing" | |
) | |
// GetStatus is the function we want to test. It just return the response.Status. | |
func GetStatus(url string) (string, error) { | |
res, err := http.Get(url) | |
if err != nil { | |
return "", err | |
} | |
return res.Status, nil | |
} | |
func TestFunc(t *testing.T) { | |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintln(w, "Hello, client") | |
})) | |
defer ts.Close() | |
status, _ := GetStatus(ts.URL) | |
if status != "200 OK" { | |
t.Fatalf("Status error: %s", status) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment