A fluent testing library for mocking http apis.
- Mock the external http apis your code is calling.
- Verify/assert the calls your code performed
func TestApiCall(t *testing.T) {
api := mockhttp.Api(t)
//...
}Note: the underlying mock server is automatically closed at the end of the test. If you need to close it earlier, you can call the
api.Close()method.
api.
Stub(http.MethodGet, "/endpoint").
WithJSON(http.StatusOK, jsonStub).
Stub(http.MethodPost, "/endpoint").
WithStatusCode(http.StatusCreated)See the StubBuilder documentation for full list of stubbing methods.
resultBasedOnMockedResponses, err := codeCallingTheApi(api.GetURL())calls := api.
Verify(http.MethodPost, "/endpoint").
HasBeenCalled(3)
expectCall1 := calls[0]
expectCall1.WithPayload(expectedPayload1)
expectCall2 := calls[1]
expectCall2.WithPayload(expectedPayload2)
expectCall2 := calls[2]
expectCall2.WithJSONPayload(map[string]any{"foo": "bar"})See CallVerifier documentation for full list of verification methods.
package main
import (
"github.com/le-yams/gomockhttp"
"fmt"
"net/http"
"testing"
)
type FooDto struct {
Foo string `json:"foo"`
}
func TestApiCall(t *testing.T) {
// Arrange
api := mockhttp.Api(t)
defer func() { api.Close() }()
api.
Stub(http.MethodGet, "/foo").
WithJson(http.StatusOK, &FooDto{Foo: "bar"})
token := "testToken"
//Act
fooService := NewFooService(api.GetUrl(), token)
foo := fooService.GetFoo() // the code actually making the http call to the api endpoint
// Assert
if foo != "bar" {
t.Errorf("unexpected value: %s\n", foo)
}
api.
Verify(http.MethodGet, "/foo").
HasBeenCalledOnce().
WithHeader("Content-Type", "application/json").
WithBearerAuthHeader(token)
}