Skip to content

Instantly share code, notes, and snippets.

@bschaatsbergen
Last active February 15, 2025 14:11
Show Gist options
  • Save bschaatsbergen/d853146a674e97f8f2b14c0df88472e3 to your computer and use it in GitHub Desktop.
Save bschaatsbergen/d853146a674e97f8f2b14c0df88472e3 to your computer and use it in GitHub Desktop.
How to mock outbound HTTP traffic in Go using `httptest`
func TestGetStatus_ReturnsActiveStatus(t *testing.T) {
// Arrange a test HTTP server on a dynamically assigned port.
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, `{"results":[{"status":"active"}]}`)
}))
defer ts.Close()
// Creates an HTTP client configured to interact with the test server.
client := Client{
client: ts.Client(),
url: ts.URL,
}
// Act
status, err := GetStatus(&client)
if err != nil {
t.Fatalf("Expected no error, got: %v", err)
}
// Assert
if status != "active" {
t.Errorf("Expected 'active', got: %s", status)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment