httpfake provides is a simple wrapper for httptest with a handful chainable API for setting up handlers to a fake server. This package is aimed to be used in tests where the original external server must not be reached. Instead is used in its place a fake server which can be configured to handle any request as desired.
go get -u github.com/maxcnunes/httpfake
or
govendor fetch github.com/maxcnunes/httpfake
If possible give preference for using vendor. This way the version is locked up as a dependency in your project.
See Releases for detailed history changes.
See godoc reference for detailed API documentation.
There are built-in methods you can use to make assertions about requests to your HTTP handlers. The currently supported assertions are:
- Presence of query parameters
- Query parameter and its expected value
- Presence of HTTP headers
- HTTP header and its expected value
- The expected body of your request
WithTesting must be provided as a server option when creating the test server if you intend to set request assertions. Failing to set the option when using request assertions will result in a panic.
You can also provide your own assertions by creating a type that implements the
Assertor interface or utilizing the
CustomAssertor function type. The Assertor.Log
method will be
called for each assertion before it's processed. The Assertor.Error
method will only be called if the
Assertor.Assert
method returns an error.
For a full list of examples please check out the functional_tests folder.
// initialize the faker server
// will bring up a httptest.Server
fakeService := httpfake.New()
// bring down the server once we
// finish running our tests
defer fakeService.Close()
// register a handler for our fake service
fakeService.NewHandler().
Get("/users").
Reply(200).
BodyString(`[{"username": "dreamer"}]`)
// run a real http request to that server
res, err := http.Get(fakeService.ResolveURL("/users"))
See the Contributing guide for steps on how to contribute to this project.
This package was heavily inspired on gock. Check that you if you prefer mocking your requests.