A new library for stubbing and mocking APIs
It’s very common to deal with code that depends on external resources, like APIs, and writing valuable tests in these cases can be challenging. There are some approaches for that, like we can mock our API clients, use a custom
http.Transport, use a real server, like
httptest.Server, with customized behavior.
I like the idea of using a real HTTP server, like
httptest.Server from Go standard library, because we can simulate real integrations, but in a controlled test environment. Another advantage of using a real server is that we won’t be tied to any specific client implementation. But for medium/large projects, it can be a problem to set up proper request assertions and response stubs using a basic server implementation. That’s where Mocha can be helpful. Mocha leverages
httptest.Server and makes it easier to create response stubs for specific request matches.
Mocha is an open-source tool to build Mock APIs in Golang, inspired by WireMock for Java.
Mocha works by running a real HTTP server and exposing a fluent API which you can easily configure response stubs for specific requests.
go get github.com/vitorsalgado/mocha/v2
It requires Go 1.18+.
Although Mocha can be used in different scenarios, its main purpose is to be used with Go tests. In typical usage, you probably gonna need to import these three packages:
github.com/vitorsalgado/mocha/v2for the core components
github.com/vitorsalgado/mocha/v2/expectimplements matching functions
github.com/vitorsalgado/mocha/v2/replyimplements response stub building functions
Usage typically looks like the example below:
In the example above, a real mock server is created using Mocha, and every time this API receives an HTTP request with the following configuration:
It will reply with:
The handler we are testing uses an API client that needs a base URL. We just need to change this base URL to point to our mock API. It is also possible to assert if the mock server received any call or a specific number of calls.
.New() function accepts a second “optional” parameter to customize the instance.
m := mocha.New(t, Configure().Addr("127.0.0.1:3000").Build())
Mocha can simulate slow responses by adding a delay to then. You can specify a duration which Mocha should wait before serving the response. See the example below:
Delay(5 * time.Second)))
Mocha provides different ways to build responses, including building response sequences, random responses, templates, use a custom function.
Below you can see some reply examples: