Lightweight HTTP mocking in Go (aka golang)

httpmock

GoDoc Go Report Card Build Status

This library builds on Go's built-in httptest library, adding a more mockable interface that can be used easily with other mocking tools like testify/mock. It does this by providing a Handler that receives HTTP components as separate arguments rather than a single *http.Request object.

Where the typical http.Handler interface is:

type Handler interface {
	ServeHTTP(ResponseWriter, *Request)
}

This library provides a server with the following interface, which works naturally with mocking libraries:

// Handler is the interface used by httpmock instead of http.Handler so that it can be mocked very easily.
type Handler interface {
	Handle(method, path string, body []byte) Response
}

Examples

The most primitive example, the OKHandler, just returns 200 OK to everything.

s := httpmock.NewServer(&httpmock.OKHandler{})
defer s.Close()

// Make any requests you want to s.URL(), using it as the mock downstream server

This example uses MockHandler, a Handler that is a testify/mock object.

downstream := &httpmock.MockHandler{}

// A simple GET that returns some pre-canned content
downstream.On("Handle", "GET", "/object/12345", mock.Anything).Return(httpmock.Response{
    Body: []byte(`{"status": "ok"}`),
})

s := httpmock.NewServer(downstream)
defer s.Close()

//
// Make any requests you want to s.URL(), using it as the mock downstream server
//

downstream.AssertExpectations(t)

If instead you wish to match against headers as well, a slightly different httpmock object can be used (please note the change in function name to be matched against):

downstream := &httpmock.MockHandlerWithHeaders{}

// A simple GET that returns some pre-canned content and a specific header
downstream.On("HandleWithHeaders", "GET", "/object/12345", MatchHeader("MOCK", "this"), mock.Anything).Return(httpmock.Response{
    Body: []byte(`{"status": "ok"}`),
})

// ... same as above

The httpmock package also provides helpers for checking calls using json objects, like so:

// This tests a hypothetical "echo" endpoint, which returns the body we pass to it.
type Obj struct {
    A string `json:"a"`
}

o := &Obj{A: "aye"}

// JSONMatcher ensures that this mock is triggered only when the HTTP body, when deserialized, matches the given
// object. Here, this mock response will get triggered only if `{"a":"aye"}` is sent.
downstream.On("Handle", "POST", "/echo", httpmock.JSONMatcher(o)).Return(httpmock.Response{
    Body: httpmock.ToJSON(o),
})
Owner
Similar Resources

Lightweight service virtualization/API simulation tool for developers and testers

Lightweight service virtualization/API simulation tool for developers and testers

API simulations for development and testing Hoverfly is a lightweight, open source API simulation tool. Using Hoverfly, you can create realistic simul

Dec 28, 2022

A lightweight load balancer used to create big Selenium clusters

A lightweight load balancer used to create big Selenium clusters

Go Grid Router Go Grid Router (aka Ggr) is a lightweight active load balancer used to create scalable and highly-available Selenium clusters. Articles

Dec 28, 2022

Lightweight selfhosted Firefox Send alternative without public upload

Lightweight selfhosted Firefox Send alternative without public upload

Gokapi Available for: Bare Metal Docker About Gokapi is a lightweight server to share files, which expire after a set amount of downloads or days. It

Jan 5, 2023

Professional lightweight testing mini-framework for Go.

Professional lightweight testing mini-framework for Go.

is Professional lightweight testing mini-framework for Go. Easy to write and read Beautifully simple API with everything you need: is.Equal, is.True,

Dec 28, 2022

Golang HTTP client testing framework

flute Golang HTTP client testing framework Presentation https://speakerdeck.com/szksh/flute-golang-http-client-testing-framework Overview flute is the

Sep 27, 2022

Extremely flexible golang deep comparison, extends the go testing package and tests HTTP APIs

Extremely flexible golang deep comparison, extends the go testing package and tests HTTP APIs

go-testdeep Extremely flexible golang deep comparison, extends the go testing package. Latest news Synopsis Description Installation Functions Availab

Dec 22, 2022

Simple HTTP integration test framework for Golang

go-itest Hassle-free REST API testing for Go. Installation go get github.com/jefflinse/go-itest Usage Create tests for your API endpoints and run the

Jan 8, 2022

Http test server written in Golang.

Dummy Server Http test server written in Golang. Can get any request method and log headers, body, path and remote address. Useful if you need to know

Oct 31, 2021

Expressive end-to-end HTTP API testing made easy in Go

baloo Expressive and versatile end-to-end HTTP API testing made easy in Go (golang), built on top of gentleman HTTP client toolkit. Take a look to the

Dec 13, 2022
Comments
  • add support for matching against header content

    add support for matching against header content

    An initial implementation of #2, if this is the desired direction to take, I will definitely need to add some more documentation, but wanted to get something that more or less works out there to get some feedback.

    • Adds a new MockHandlerWithHeaders which expects calls to HandleWithHeaders instead of Handle
    • Adds SingleHeaderMatcher and MultiHeaderMatcher helpers to match against the presences and content of headers.
  • Pass URL.RequestURI() to Handler so query is included

    Pass URL.RequestURI() to Handler so query is included

    I was writing a test that involved the client sending a query string and noticed that the query string didn't seem to be making it to the MockHandler I created. After digging into the httpmock code I noticed that the Handler was being passed URL.Path, which is just the bare path part of the URI.

    Using URL.RequestURI() instead of URL.Path ensures that any query parameters sent by the client are included when invoking the Handler.

    For example, before this change, if a client requested GET /foo?bar=baz the Handle method would be invoked with a path of /foo. With this change the full path + query is passed to Handle: /foo?bar=baz.

  • Better Header Support

    Better Header Support

    Currently if you want to match headers, you have to provide all the headers, including Content-Length, User-Agent, etc. For a a matched endpoint. This would be better if it'd just check if the given headers were included instead, and ignore everything else.

    I see in the readme there's a reference to a MatchHeaders function, but I don't see that anywhere in the code.

  • Handle Headers

    Handle Headers

    I haven't personally had a need for this yet, but it would be nice at some point to handle expected request headers like so:

    type HandlerWithHeader interface {
    	HandleWithHeader(method, path string, body []byte, header http.Header) Response
    }
    
HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽

gock Versatile HTTP mocking made easy in Go that works with any net/http based stdlib implementation. Heavily inspired by nock. There is also its Pyth

Jan 4, 2023
HTTP mocking to test API services for chaos scenarios
HTTP mocking to test API services for chaos scenarios

GAOS HTTP mocking to test API services for chaos scenarios Gaos, can create and provide custom mock restful services via using your fully-customizable

Nov 5, 2022
A simple and expressive HTTP server mocking library for end-to-end tests in Go.

mockhttp A simple and expressive HTTP server mocking library for end-to-end tests in Go. Installation go get -d github.com/americanas-go/mockhttp Exa

Dec 19, 2021
Go Interface Mocking Tool

Charlatan Percolate's Go Interface Mocking Tool. Please read our introductory blog post. Installation go get github.com/percolate/charlatan Usage c

Nov 3, 2022
GoMock is a mocking framework for the Go programming language.

gomock GoMock is a mocking framework for the Go programming language. It integrates well with Go's built-in testing package, but can be used in other

Dec 28, 2022
A clipboard-based mocking framework for Go that gets out of your way.
A clipboard-based mocking framework for Go that gets out of your way.

A clipboard-based mocking framework for Go that gets out of your way. This tool has been built with inspiration lovingly taken from Moq, and fuelled b

Nov 18, 2022
Full-featured test framework for Go! Assertions, mocking, input testing, output capturing, and much more! 🍕
Full-featured test framework for Go! Assertions, mocking, input testing, output capturing, and much more! 🍕

testza ?? Testza is like pizza for Go - you could life without it, but why should you? Get The Module | Documentation | Contributing | Code of Conduct

Dec 10, 2022
Interface mocking tool for go generate
Interface mocking tool for go generate

Interface mocking tool for go generate. What is Moq? Moq is a tool that generates a struct from any interface. The struct can be used in test code as

Jan 5, 2023
A basic lightweight HTTP client for Go with included mock features.

A basic lightweight HTTP client for Go with included mock features. Features Support almost all http method like G

May 2, 2022
HTTP mock for Golang: record and replay HTTP/HTTPS interactions for offline testing

govcr A Word Of Warning I'm in the process of partly rewriting govcr to offer better support for cassette mutations. This is necessary because when I

Dec 28, 2022