How to Mock HTTP Calls in Go (httptest)

Mock HTTP calls in Go by using net/http/httptest to create in-memory servers and recorders for testing handlers without network I/O.

Use net/http/httptest to create an in-memory server that handles requests without network I/O. This allows you to test HTTP handlers by sending requests to the server and asserting the response directly in your test function.

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestHandler(t *testing.T) {
	// Create a test server with your handler
	req := httptest.NewRequest("GET", "/", nil)
	rr := httptest.NewRecorder()

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("Hello"))
	})

	// Serve the request
	handler.ServeHTTP(rr, req)

	// Assert status and body
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
	}
	if rr.Body.String() != "Hello" {
		t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), "Hello")
	}
}