http_mock

package module
v0.0.0-...-be47163 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2018 License: MIT Imports: 1 Imported by: 0

README

http-mock

A package that help you create mock http call for unit test.

Install

$ go get -u github.com/khanhtc1202/http-mock

Usage

All usage and examples are described in GoDoc.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func MockHandleClient

func MockHandleClient(fn RoundTripFunc) *http.Client

Mock http.Client by HandleFunction

returns *http.Client with Transport replaced with handle mechanism that passed as function parameter.

Example
requiredUrl := "http://some-path"
expectedRes := `whatever`

mockClient := http_mock.MockHandleClient(func(req *http.Request) *http.Response {
	// Do stub with request object
	if req.URL.String() == requiredUrl {
		fmt.Println(req.URL.String())
	}

	return &http.Response{
		// Mocked status code
		StatusCode: 200,
		// Mocked response for testing
		Body: ioutil.NopCloser(bytes.NewBufferString(expectedRes)),
		// Mocked header
		// Header: make(http.Header),
	}
})

doStubObj := doStubObject{client: mockClient}
res, _ := doStubObj.RequestHttp(requiredUrl)
fmt.Println(res)
Output:

http://some-path
whatever

func MockResponseClient

func MockResponseClient(res *http.Response) *http.Client

Mock http.Client by ExpectedResponse

returns *http.Client with Transport replaced and always returns defined http.Response as a response from http call.

Example
expectedResBody := `whatever`
expectedRes := http.Response{
	StatusCode: 200,
	Body:       ioutil.NopCloser(bytes.NewBufferString(expectedResBody)),
}

mockClient := http_mock.MockResponseClient(&expectedRes)

doStubObj := doStubObject{client: mockClient}
res, _ := doStubObj.RequestHttp("http://....")
fmt.Println(res)
Output:

whatever

Types

type RoundTripFunc

type RoundTripFunc func(req *http.Request) *http.Response

An implement of Transport interface (from net/http Client)

Transport specifies the mechanism by which individual HTTP requests are made.

func (RoundTripFunc) RoundTrip

func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip executes a single HTTP transaction, returning a Response for the provided Request.

Override it with own implementation to control http request with the interface:

input: http.Request output: http.Response

Jump to

Keyboard shortcuts

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