Skip to content

Latest commit

 

History

History
106 lines (81 loc) · 3.14 KB

File metadata and controls

106 lines (81 loc) · 3.14 KB

gomockhttp

Version Coverage Status Go Report Card GoDoc License FOSSA Status FOSSA Status

A fluent testing library for mocking http apis.

  • Mock the external http apis your code is calling.
  • Verify/assert the calls your code performed

Getting started

1. Create the API mock

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.

2. Stub endpoints

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.

3. Call the mocked API

resultBasedOnMockedResponses, err := codeCallingTheApi(api.GetURL())

4. Verify the API invocations

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.

Example

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)
}