https://github.com/bool64/httpmock
Configurable mock for HTTP client and server
https://github.com/bool64/httpmock
Last synced: about 2 months ago
JSON representation
Configurable mock for HTTP client and server
- Host: GitHub
- URL: https://github.com/bool64/httpmock
- Owner: bool64
- License: mit
- Created: 2021-10-21T08:05:04.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2024-10-30T14:08:36.000Z (over 1 year ago)
- Last Synced: 2024-10-30T14:45:46.980Z (over 1 year ago)
- Language: Go
- Homepage:
- Size: 74.2 KB
- Stars: 2
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# httpmock
[](https://github.com/bool64/httpmock/actions?query=branch%3Amaster+workflow%3Atest-unit)
[](https://codecov.io/gh/bool64/httpmock)
[](https://pkg.go.dev/github.com/bool64/httpmock)
[](https://wakatime.com/badge/github/bool64/httpmock)


HTTP Server and Client mocks for Go.
## Example
```go
// 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:
//
```