httpmock: github.com/jarcoal/httpmock Index | Files

package httpmock

import "github.com/jarcoal/httpmock"

HTTPmock provides tools for mocking HTTP responses.

Simple Example:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	defer httpmock.DeactivateAndReset()

	httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles.json",
		httpmock.NewStringResponder(200, `[{"id": 1, "name": "My Great Article"}]`))

	// do stuff that makes a request to articles.json
}

Advanced Example:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	defer httpmock.DeactivateAndReset()

	// our database of articles
	articles := make([]map[string]interface{}, 0)

	// mock to list out the articles
	httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles.json",
		func(req *http.Request) (*http.Response, error) {
			resp, err := httpmock.NewJsonResponse(200, articles)
			if err != nil {
				return httpmock.NewStringResponse(500, ""), nil
			}
			return resp
		},
	)

	// mock to add a new article
	httpmock.RegisterResponder("POST", "https://api.mybiz.com/articles.json",
		func(req *http.Request) (*http.Response, error) {
			article := make(map[string]interface{})
			if err := json.NewDecoder(req.Body).Decode(&article); err != nil {
				return httpmock.NewStringResponse(400, ""), nil
			}

			articles = append(articles, article)

			resp, err := httpmock.NewJsonResponse(200, article)
			if err != nil {
				return httpmock.NewStringResponse(500, ""), nil
			}
			return resp, nil
		},
	)

	// do stuff that adds and checks articles
}

Index

Package Files

doc.go env.go response.go transport.go

Variables

var DefaultTransport = NewMockTransport()

DefaultTransport is the default mock transport used by Activate, Deactivate, Reset, DeactivateAndReset, RegisterResponder, and RegisterNoResponder.

var InitialTransport = http.DefaultTransport

InitialTransport is a cache of the original transport used so we can put it back when Deactivate is called.

var NoResponderFound = errors.New("no responder found")

NoResponderFound is returned when no responders are found for a given HTTP method and URL.

func Activate Uses

func Activate()

Activate starts the mock environment. This should be called before your tests run. Under the hood this replaces the Transport on the http.DefaultClient with DefaultTransport.

To enable mocks for a test, simply activate at the beginning of a test:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	// all http requests will now be intercepted
}

If you want all of your tests in a package to be mocked, just call Activate from init():

func init() {
	httpmock.Activate()
}

func ActivateNonDefault Uses

func ActivateNonDefault(client *http.Client)

ActivateNonDefault starts the mock environment with a non-default http.Client. This emulates the Activate function, but allows for custom clients that do not use http.DefaultTransport

To enable mocks for a test using a custom client, activate at the beginning of a test:

client := &http.Client{Transport: &http.Transport{TLSHandshakeTimeout: 60 * time.Second}}
httpmock.ActivateNonDefault(client)

func ConnectionFailure Uses

func ConnectionFailure(*http.Request) (*http.Response, error)

ConnectionFailure is a responder that returns a connection failure. This is the default responder, and is called when no other matching responder is found.

func Deactivate Uses

func Deactivate()

Deactivate shuts down the mock environment. Any HTTP calls made after this will use a live transport.

Usually you'll call it in a defer right after activating the mock environment:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	defer httpmock.Deactivate()

	// when this test ends, the mock environment will close
}

func DeactivateAndReset Uses

func DeactivateAndReset()

DeactivateAndReset is just a convenience method for calling Deactivate() and then Reset() Happy deferring!

func Disabled Uses

func Disabled() bool

func NewBytesResponse Uses

func NewBytesResponse(status int, body []byte) *http.Response

NewBytesResponse creates an *http.Response with a body based on the given bytes. Also accepts an http status code.

func NewJsonResponse Uses

func NewJsonResponse(status int, body interface{}) (*http.Response, error)

NewJsonResponse creates an *http.Response with a body that is a json encoded representation of the given interface{}. Also accepts an http status code.

func NewRespBodyFromBytes Uses

func NewRespBodyFromBytes(body []byte) io.ReadCloser

NewRespBodyFromBytes creates an io.ReadCloser from a byte slice that is suitable for use as an http response body.

func NewRespBodyFromString Uses

func NewRespBodyFromString(body string) io.ReadCloser

NewRespBodyFromString creates an io.ReadCloser from a string that is suitable for use as an http response body.

func NewStringResponse Uses

func NewStringResponse(status int, body string) *http.Response

NewStringResponse creates an *http.Response with a body based on the given string. Also accepts an http status code.

func NewXmlResponse Uses

func NewXmlResponse(status int, body interface{}) (*http.Response, error)

NewXmlResponse creates an *http.Response with a body that is an xml encoded representation of the given interface{}. Also accepts an http status code.

func RegisterNoResponder Uses

func RegisterNoResponder(responder Responder)

RegisterNoResponder adds a mock that will be called whenever a request for an unregistered URL is received. The default behavior is to return a connection error.

In some cases you may not want all URLs to be mocked, in which case you can do this:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	httpmock.DeactivateAndReset()
	httpmock.RegisterNoResponder(httpmock.InitialTransport.RoundTrip)

	// any requests that don't have a registered URL will be fetched normally
}

func RegisterResponder Uses

func RegisterResponder(method, url string, responder Responder)

RegisterResponder adds a mock that will catch requests to the given HTTP method and URL, then route them to the Responder which will generate a response to be returned to the client.

Example:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	httpmock.DeactivateAndReset()

	httpmock.RegisterResponder("GET", "http://example.com/",
		httpmock.NewStringResponder(200, "hello world"))

	// requests to http://example.com/ will now return 'hello world'
}

func Reset Uses

func Reset()

Reset will remove any registered mocks and return the mock environment to it's initial state.

type MockTransport Uses

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

MockTransport implements http.RoundTripper, which fulfills single http requests issued by an http.Client. This implementation doesn't actually make the call, instead deferring to the registered list of responders.

func NewMockTransport Uses

func NewMockTransport() *MockTransport

NewMockTransport creates a new *MockTransport with no responders.

func (*MockTransport) CancelRequest Uses

func (m *MockTransport) CancelRequest(req *http.Request)

do nothing with timeout

func (*MockTransport) RegisterNoResponder Uses

func (m *MockTransport) RegisterNoResponder(responder Responder)

RegisterNoResponder is used to register a responder that will be called if no other responder is found. The default is ConnectionFailure.

func (*MockTransport) RegisterResponder Uses

func (m *MockTransport) RegisterResponder(method, url string, responder Responder)

RegisterResponder adds a new responder, associated with a given HTTP method and URL. When a request comes in that matches, the responder will be called and the response returned to the client.

func (*MockTransport) Reset Uses

func (m *MockTransport) Reset()

Reset removes all registered responders (including the no responder) from the MockTransport

func (*MockTransport) RoundTrip Uses

func (m *MockTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip receives HTTP requests and routes them to the appropriate responder. It is required to implement the http.RoundTripper interface. You will not interact with this directly, instead the *http.Client you are using will call it for you.

type Responder Uses

type Responder func(*http.Request) (*http.Response, error)

Responders are callbacks that receive and http request and return a mocked response.

func NewBytesResponder Uses

func NewBytesResponder(status int, body []byte) Responder

NewBytesResponder creates a Responder from a given body (as a byte slice) and status code.

func NewJsonResponder Uses

func NewJsonResponder(status int, body interface{}) (Responder, error)

NewJsonResponder creates a Responder from a given body (as an interface{} that is encoded to json) and status code.

func NewStringResponder Uses

func NewStringResponder(status int, body string) Responder

NewStringResponder creates a Responder from a given body (as a string) and status code.

func NewXmlResponder Uses

func NewXmlResponder(status int, body interface{}) (Responder, error)

NewXmlResponder creates a Responder from a given body (as an interface{} that is encoded to xml) and status code.

func ResponderFromResponse Uses

func ResponderFromResponse(resp *http.Response) Responder

ResponderFromResponse wraps an *http.Response in a Responder

Package httpmock imports 9 packages (graph) and is imported by 4 packages. Updated 2018-11-10. Refresh now. Tools for package owners.