Last active
February 15, 2025 14:11
-
-
Save bschaatsbergen/d853146a674e97f8f2b14c0df88472e3 to your computer and use it in GitHub Desktop.
How to mock outbound HTTP traffic in Go using `httptest`
This file contains hidden or 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
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