Skip to content

bool64/httpmock

Folders and files

NameName
Last commit message
Last commit date
Oct 30, 2024
Oct 21, 2021
Oct 30, 2024
Oct 21, 2021
Oct 30, 2024
Oct 21, 2021
Oct 31, 2024
Oct 30, 2024
Oct 21, 2021
Oct 21, 2021
Oct 21, 2021
Oct 30, 2024
Oct 30, 2024
Dec 2, 2022
Jun 24, 2024

Repository files navigation

httpmock

Build Status Coverage Status GoDevDoc Time Tracker Code lines Comments

HTTP Server and Client mocks for Go.

Example

// Prepare server mock.
sm, url := httpmock.NewServer()
defer sm.Close()

// This example shows Client and Server working together for sake of portability.
// In real-world scenarios Client would complement real server or Server would complement real HTTP client.

// Set successful expectation for first request out of concurrent batch.
exp := httpmock.Expectation{
    Method:     http.MethodPost,
    RequestURI: "/foo?q=1",
    RequestHeader: map[string]string{
        "X-Custom":     "def",
        "X-Header":     "abc",
        "Content-Type": "application/json",
    },
    RequestBody:  []byte(`{"foo":"bar"}`),
    Status:       http.StatusAccepted,
    ResponseBody: []byte(`{"bar":"foo"}`),
}
sm.Expect(exp)

// Set failing expectation for other requests of concurrent batch.
exp.Status = http.StatusConflict
exp.ResponseBody = []byte(`{"error":"conflict"}`)
exp.Unlimited = true
sm.Expect(exp)

// Prepare client request.
c := httpmock.NewClient(url)
c.ConcurrencyLevel = 50
c.Headers = map[string]string{
    "X-Header": "abc",
}

c.Reset().
    WithMethod(http.MethodPost).
    WithHeader("X-Custom", "def").
    WithContentType("application/json").
    WithBody([]byte(`{"foo":"bar"}`)).
    WithURI("/foo?q=1").
    Concurrently()

// Check expectations errors.
fmt.Println(
    c.ExpectResponseStatus(http.StatusAccepted),
    c.ExpectResponseBody([]byte(`{"bar":"foo"}`)),
    c.ExpectOtherResponsesStatus(http.StatusConflict),
    c.ExpectOtherResponsesBody([]byte(`{"error":"conflict"}`)),
)

// Output:
// <nil> <nil> <nil> <nil>