Skip to content

le-yams/gomockhttp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

76ddbcf · Nov 27, 2024

History

19 Commits
Oct 15, 2024
Jun 29, 2023
Oct 15, 2024
Jun 29, 2023
Jul 5, 2023
Nov 25, 2024
Oct 15, 2024
Nov 27, 2024
Nov 27, 2024
Nov 25, 2024
Oct 30, 2024
Nov 25, 2024
Nov 22, 2024
Nov 25, 2024
Nov 25, 2024

Repository files navigation

gomockhttp

Build Status Coverage Status Go Report Card GoDoc Version

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

Create the API mock

func TestApiCall(t *testing.T) {
  api := mockhttp.Api(t)
  defer func() { api.Close() }()
  //...
}

Stub endpoints

api.
  Stub(http.MethodGet, "/endpoint").
  WithJson(http.StatusOK, jsonStub).

  Stub(http.MethodPost, "/endpoint").
  WithStatusCode(http.StatusCreated)

Call the mocked API

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

Verify the API invocations

calls := api.
  Verify(http.MethodPost, "/endpoint").
  HasBeenCalled(2)

expectCall1 := calls[0]
expectCall1.WithPayload(expectedPayload1)

expectCall2 := calls[1]
expectCall2.WithPayload(expectedPayload2)

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("Authorization", fmt.Sprintf("Bearer %s", token))
}

About

Go library for mocking http APIs

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages