Skip to content

Instantly share code, notes, and snippets.

@riethm
Last active September 15, 2016 13:22
Show Gist options
  • Save riethm/a95b768500572135b30c3c8847be0ada to your computer and use it in GitHub Desktop.
Save riethm/a95b768500572135b30c3c8847be0ada to your computer and use it in GitHub Desktop.
golang httpmock augmented with assertions
import (
"testing"
"github.com/jarcoal/httpmock"
"net/http"
"io/ioutil"
)
type Call struct {
req *http.Request
resp *http.Response
}
type MockEndpoint struct {
responder httpmock.Responder
Calls []Call
}
func NewMockEndpoint(wrappedResponder httpmock.Responder) MockEndpoint {
mock := MockEndpoint{
responder: wrappedResponder,
Calls: []Call{},
}
return mock
}
func (r *MockEndpoint) GetResponder() httpmock.Responder {
return func(req *http.Request) (resp *http.Response, err error) {
resp, err = r.responder(req)
r.Calls = append(r.Calls, Call{req: req, resp: resp})
return
}
}
func (r MockEndpoint) AssertCalled() bool {
return len(r.Calls) > 0
}
func (r MockEndpoint) AssertCalledWithBody(body string) bool {
for _, call := range r.Calls {
b, err := ioutil.ReadAll(call.req.Body)
if err != nil {
continue
}
if string(b) == body {
return true
}
}
return false
}
func (r MockEndpoint) AssertCalledWithQueryParam(key string, value string) bool {
for _, call := range r.Calls {
if call.req.URL.Query().Get(key) == value {
return true
}
}
return false
}
func (r MockEndpoint) AssertCalledOnce() bool {
return r.AssertCallCount(1)
}
func (r MockEndpoint) AssertCallCount(count int) bool {
return r.CallCount() == count
}
func (r MockEndpoint) CallCount() int {
return len(r.Calls)
}
var baseURL = "..."
func TestFoo(t *testing.T) {
httpmock.Activate()
defer httpmock.Deactivate()
mock := NewMockEndpoint(httpmock.NewStringResponder(200, "bar"))
httpmock.RegisterResponder(
"GET",
baseURL + "/foo",
mock.GetResponder(),
)
// do something which invokes the /foo endpoint
// Assertions:
if !mock.AssertCalled() {
t.Errorf("/foo not called")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment