Skip to content
Simple http client mock tool
Go
Branch: master
Clone or download
Latest commit 7c242a4 Dec 1, 2017
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.travis.yml enabled travis-ci Dec 1, 2017
README.md enabled travis-ci Dec 1, 2017
mock.go following empty content Dec 1, 2017
mock_test.go following empty content Dec 1, 2017

README.md

go-mock-http-response

Simple http client mock tool.

Build Status codecov GoDoc

SYNOPSIS

package main

import (
    "io/ioutil"
    "net/http"
    "testing"

    mockhttp "github.com/karupanerura/go-mock-http-response"
)

func mockResponse(statusCode int, headers map[string]string, body []byte) {
    http.DefaultClient = mockhttp.NewResponseMock(statusCode, headers, body).MakeClient()
}

func checkFoo() (bool, error) {
    res, err := http.Get("http://example.com/")
    if err != nil {
        return false, err
    }
    defer res.Body.Close()

    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        return false, err
    }

    isFoo := string(body) == "foo"
    return isFoo, nil
}

func TestFoo(t *testing.T) {
    mockResponse(http.StatusOK, map[string]string{"Content-Type": "text/plain"}, []byte("foo"))
    isFoo, err := checkFoo()
    if err != nil {
        t.Fatal(err)
    }
    if isFoo != true {
        t.Errorf("Should be true, but got false")
    }

    mockResponse(http.StatusOK, map[string]string{"Content-Type": "text/plain"}, []byte("bar"))
    isFoo, err = checkFoo()
    if err != nil {
        t.Fatal(err)
    }
    if isFoo != false {
        t.Errorf("Should be false, but got true")
    }
}
You can’t perform that action at this time.