Building Mock APIs in Golang with Mocha

A new library for stubbing and mocking APIs

Photo by AltumCode on Unsplash

Hello developers! Recently, I published Mocha, a library written in Go to build mock APIs, inspired by WireMock from the Java world. This article will give a brief overview of this new project.

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

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:

  • for the core components
  • implements matching functions
  • implements 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:

GET /customers/super-id
accept: application/json
content-type: application/json

It will reply with:

200 OK 
{id:”super-id”, name:”nice-name”}

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.


Mochas’ .New() function accepts a second “optional” parameter to customize the instance.

m := mocha.New(t, Configure().Addr("").Build())

Delaying Responses

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:

News Credit

%d bloggers like this: