Skip to content

Instantly share code, notes, and snippets.

@efueyo
Last active October 29, 2019 22:25
Show Gist options
  • Save efueyo/469576e9b416cf28736abbc4af80e2ac to your computer and use it in GitHub Desktop.
Save efueyo/469576e9b416cf28736abbc4af80e2ac to your computer and use it in GitHub Desktop.
httptest.Server example
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