• Stars
    star
    4
  • Rank 3,303,977 (Top 66 %)
  • Language
    Go
  • Created over 4 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Webmock for Golang, to stub requests.

Webmock

This package creates a HTTP server, it stubs requests. Inspired by bblimke/webmock. It's useful when writing integration tests while code reply on external requests. With webmock, just point the endpoint/host to mock server and stub the requests.

Webmock takes a different approach compared with gock or httpmock, it doesn't intercept http Client and replace http Transport. It runs a web server, whenever comes a request, it tries to match the request and return stub response.

Examples

Start mock server

server := webmock.New()
baseURL := server.URL()

server.Start()

Stubbed request based on method, url

server.Stub("GET", "/hello", "ok")
server.Stub("POST", "/hello", "ok-post")

// curl http://server/hello
// curl -XPOST http://server/hello

Stubbed request based on method, url and headers

server.Stub(
    "GET",
    "/hello",
    "ok",
    webmock.WithHeaders("Content-Type: application/json"),
)

// curl -H "Content-Type: application/json" http://server/hello

Stubbing with custom response

server.Stub(
  "GET",
  "/abc?foo=bar",
  "",
  webmock.WithHeaders("Accept: application/json"),
  webmock.WithResponse(500, "Ah oh", map[string]string{
    "Access-Control-Allow-Origin": "*",
    "Content-Type":                "application/xml",
  }),
)

// curl -i -H "Content-Type: application/json" http://server/abc?foo=bar

Load cassettes

// Load a directory
server.LoadCassette("./fixtures")

// Load a yaml file
server.LoadCassette("./fixtures/sample_cassette.yml")