mockhttp

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 14, 2025 License: MIT Imports: 11 Imported by: 0

README

gomockhttp

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIMock added in v0.1.1

type APIMock struct {
	// contains filtered or unexported fields
}

APIMock is a representation of a mocked API. It allows to stub HTTP calls and verify invocations.

func API added in v0.1.1

func API(testState TestingT) *APIMock

API creates a new APIMock instance and starts a server exposing it.

func (*APIMock) Close added in v0.1.1

func (mockedAPI *APIMock) Close()

Close stops the underlying server.

func (*APIMock) GetHost added in v0.1.1

func (mockedAPI *APIMock) GetHost() string

GetHost returns the host of the API underlying server.

func (*APIMock) GetURL added in v0.1.1

func (mockedAPI *APIMock) GetURL() *url.URL

GetURL returns the URL of the API underlying server.

func (*APIMock) Stub added in v0.1.1

func (mockedAPI *APIMock) Stub(method string, path string) *StubBuilder

Stub creates a new StubBuilder instance for the given method and path.

func (*APIMock) Verify added in v0.1.1

func (mockedAPI *APIMock) Verify(method string, path string) *CallVerifier

Verify creates a new CallVerifier instance for the given method and path.

type CallVerifier added in v0.1.0

type CallVerifier struct {
	// contains filtered or unexported fields
}

CallVerifier is a helper to verify invocations of a specific HTTP call

func (*CallVerifier) HasBeenCalled added in v0.1.0

func (verifier *CallVerifier) HasBeenCalled(expectedCallsCount int) []*Invocation

HasBeenCalled asserts that the HTTP call has been made the expected number of times. It returns all invocations of the call.

func (*CallVerifier) HasBeenCalledOnce added in v0.1.0

func (verifier *CallVerifier) HasBeenCalledOnce() *Invocation

HasBeenCalledOnce asserts that the HTTP call has been made exactly once then returns the invocation.

func (*CallVerifier) HasNotBeenCalled added in v0.5.0

func (verifier *CallVerifier) HasNotBeenCalled()

HasNotBeenCalled asserts that no HTTP call has been made.

type HTTPCall added in v0.1.1

type HTTPCall struct {
	Method string
	Path   string
}

HTTPCall is a simple representation of an endpoint call.

type Invocation

type Invocation struct {
	// contains filtered or unexported fields
}

Invocation represents a single HTTP request made to the mock server.

func (*Invocation) GetPayload added in v0.1.0

func (call *Invocation) GetPayload() []byte

GetPayload returns the invocation request payload

func (*Invocation) GetRequest added in v0.1.0

func (call *Invocation) GetRequest() *http.Request

GetRequest returns the invocation request

func (*Invocation) ReadJSONPayload added in v0.1.1

func (call *Invocation) ReadJSONPayload(obj any)

ReadJSONPayload reads the invocation request payload and unmarshals it into the specified object

func (*Invocation) WithHeader added in v0.1.0

func (call *Invocation) WithHeader(name string, expectedValues ...string) *Invocation

WithHeader asserts that the invocation request contains the specified header

func (*Invocation) WithPayload added in v0.1.0

func (call *Invocation) WithPayload(expected []byte) *Invocation

WithPayload asserts that the invocation request contains the specified payload

func (*Invocation) WithQueryValue added in v1.0.0

func (call *Invocation) WithQueryValue(name string, value string) *Invocation

func (*Invocation) WithQueryValues added in v1.0.0

func (call *Invocation) WithQueryValues(values map[string]string) *Invocation

func (*Invocation) WithQueryValuesExactly added in v1.0.0

func (call *Invocation) WithQueryValuesExactly(values map[string]string) *Invocation

func (*Invocation) WithStringPayload added in v0.1.0

func (call *Invocation) WithStringPayload(expected string) *Invocation

WithStringPayload asserts that the invocation request contains the specified string payload

func (*Invocation) WithUrlEncodedFormPayload added in v0.3.0

func (call *Invocation) WithUrlEncodedFormPayload() *InvocationRequestForm

WithUrlEncodedFormPayload assert that the invocation content type is application/x-www-form-urlencoded then returns the form to be asserted.

func (*Invocation) WithoutHeader added in v0.1.0

func (call *Invocation) WithoutHeader(name string) *Invocation

WithoutHeader asserts that the invocation request does not contain the specified header

type InvocationRequestForm added in v0.3.0

type InvocationRequestForm struct {
	// contains filtered or unexported fields
}

InvocationRequestForm represents a form payload of an HTTP request made to the mock server.

func (InvocationRequestForm) Get added in v1.0.0

func (form InvocationRequestForm) Get(s string) string

func (InvocationRequestForm) WithValue added in v1.0.0

func (form InvocationRequestForm) WithValue(key string, value string) InvocationRequestForm

func (InvocationRequestForm) WithValues added in v0.3.0

func (form InvocationRequestForm) WithValues(expectedValues map[string]string) InvocationRequestForm

WithValues asserts that the form contains at least the specified values

func (InvocationRequestForm) WithValuesExactly added in v0.3.0

func (form InvocationRequestForm) WithValuesExactly(expectedValues map[string]string) InvocationRequestForm

WithValuesExactly asserts that the form contains exactly the specified values

type StubBuilder

type StubBuilder struct {
	// contains filtered or unexported fields
}

StubBuilder is a helper to build stubs for a specific HTTP call

func (*StubBuilder) With

func (stub *StubBuilder) With(handler http.HandlerFunc) *APIMock

With creates a new stub for the HTTP call with the specified handler

func (*StubBuilder) WithBody added in v0.2.0

func (stub *StubBuilder) WithBody(statusCode int, body []byte, contentType string) *APIMock

WithBody creates a new stub handler returning the specified status code and body content.

func (*StubBuilder) WithDelay added in v0.4.0

func (stub *StubBuilder) WithDelay(delay time.Duration) *StubBuilder

WithDelay adds a delay to the stub when called before it executes the corresponding handler

func (*StubBuilder) WithJSON added in v0.1.1

func (stub *StubBuilder) WithJSON(statusCode int, content interface{}) *APIMock

WithJSON creates a new stub handler returning the specified status code and JSON content. The response header "Content-Type" is set to "application/json".

func (*StubBuilder) WithStatusCode added in v0.1.0

func (stub *StubBuilder) WithStatusCode(statusCode int) *APIMock

WithStatusCode creates a new stub handler returning the specified status code

type TestingT added in v0.1.0

type TestingT interface {
	Error(args ...any)
	Errorf(format string, args ...any)
	Fatal(args ...any)
	Fatalf(format string, args ...any)
}

TestingT is an interface wrapper around *testing.T.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL