Skip to content

A package that creates a testable http.Client that allows for returning fake data as well as verifying expectations were met.

License

Notifications You must be signed in to change notification settings

MordFustang21/clientmock

Repository files navigation

clientmock

GoDoc Go Report Card codecov

A mockable http.Client used to validate request data and return fake response data by replacing the http.Client transport layer.

Install

go get github.com/MordFustang21/clientmock

Documentation and Examples

Example returning status code and body

package main

import (
	"bytes"
	"io/ioutil"
	"net/http"
	"testing"
	
	"github.com/MordFustang21/clientmock"
)

func TestGet(t *testing.T) {
	client, mock, err := clientmock.NewClient()
	if err != nil {
		t.Fatal(err)
	}
	
	expectedStatus := http.StatusBadRequest
	expectedBody := "empty request body"
	
	mock.ReturnStatus(expectedStatus)
	mock.ReturnBody(bytes.NewBufferString(expectedBody))
	
	req, err := http.NewRequest(http.MethodPost, "http://www.github.com", nil)
	if err != nil {
		t.Fatal(err)
	}
	
	res, err := client.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()
	
	// Status code will be 400 as defined in mock
	if res.StatusCode != expectedStatus {
		t.Fatal("got wrong status")
	}
	
	// body will contain "empty request body" as defined in mock
	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		t.Fatal(err)
	}
	
	if string(data) != expectedBody {
		t.Fatal("returned body doesn't match expected")
	}
}

Contributions

Feel free to open a pull request. Note, if you wish to contribute an extension to public (exported methods or types) - please open an issue before, to discuss whether these changes can be accepted. All backward incompatible changes are and will be treated cautiously

License

The GNU General Public License V3.0

About

A package that creates a testable http.Client that allows for returning fake data as well as verifying expectations were met.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages