http-mock: github.com/khanhtc1202/http-mock Index | Examples | Files

package http_mock

import "github.com/khanhtc1202/http-mock"

Index

Examples

Package Files

httpmock.go

func MockHandleClient Uses

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.

Code:

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 Uses

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.

Code:

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

type RoundTripFunc Uses

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 Uses

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

Package http_mock imports 1 packages (graph). Updated 2018-11-27. Refresh now. Tools for package owners.