How to mock http.Client that returns a JSON response

golang mock http client
golang mock json response
golang intercept http request
golang test json response
golang mock request context
golang mock return error
golang http client interface
golang mock return different values

I'm trying to test a method that uses net/http to make requests. Specifically what I'm trying to achieve is to inject a mock http.Client that responds with a certain JSON body

type clientMock struct{}

func (c *clientMock) Do(req *http.Request) (*http.Response, error) {
  json := struct {
    AccessToken string `json:"access_token`
    Scope       string `json:"scope"`
  }{
    AccessToken: "123457678",
    Scope:       "read, write",
  }
  body := json.Marshal(json)
  res := &http.Response {
    StatusCode: http.StatusOK,
    Body:       // I haven't got a clue what to put here
  }
  return res
}

func TestRequest(t *testing.T) { //tests here }

I do know that the Body is of a type io.ReadCloser interface. Trouble is I can't for the life of me find a way to implement it in the mock body response.

Examples as found here so far only demonstrates returning a blank &http.Response{}

While it's probably more useful to mock the full request cycle with httptest.Server, you can use ioutil.NopCloser to create the closer around any reader:

Body: ioutil.NopCloser(bytes.NewReader(body))

and if you want an empty body, just provider a reader with no content.

Body: ioutil.NopCloser(bytes.NewReader(nil))

HTTP Unit Testing, The following simple example generates a basic HttpResponse : HttpTransport transport = new MockHttpTransport(); HttpRequest request =  Yes, you must test your code 😃. To be able to test the code, you need to simulate the server response. You can create an interface and use a mock library to replace the HttpClient. But I prefer keeping the HttpClient in the code because it's the main part of the code. So, let's use another way.

In your test file (my_test.go):

type MyJSON struct {
        Id          string
        Age         int
}

// Interface which is the same as httpClient because it implements "Do" method.
type ClientMock struct {}

func (c *ClientMock) Do(req *http.Request) (*http.Response, error) {
    mockedRes := MyJSON {"1", 3}

    // Marshal a JSON-encoded version of mockedRes
    b, err := json.Marshal(mockedRes)
    if err != nil {
        log.Panic("Error reading a mockedRes from mocked client", err)
    }

    return &http.Response{Body: ioutil.NopCloser(bytes.NewBuffer(b))}, nil
}

// your test which will use the mocked response
func TestMyFunction(t *testing.T) {

    mock := &ClientMock{}
    actualResult := myFunction(mock)
    assert.NotEmpty(t, actualResult, "myFunction should have at least 1 result")

}

In your implementation (main.go):

package main

import (
    "net/http"
)

func main() {
    myFunction(&http.Client{})
}

Mocking HTTP Requests in Golang, Response, error) {. jsonBytes, err := json.Marshal(body). if err != nil {. return nil, err. } request, err := http.NewRequest(http.MethodPost, url, bytes  - in your mock service, go into your mock response - in the mock response, enter your JSON content to return from the mock service - on bottom of response editor expand the headers tab and enter: Header = Content-Type Value=application/json that for me returns JSON response with the right header. Michael Giller SmartBear Software

I know it's been a little while but I just wrote something to help with this recently.

Like JimB I recommend starting up a real HTTP server locally, since in Go this is easy to do with https://golang.org/pkg/net/http/httptest/.

However having done a lot of HTTP mocking I wanted something that does a little more, like a good mock library would: returning specific data, easy setting of expectations, validation that all requests were made, etc. I have generally used https://godoc.org/github.com/stretchr/testify/mock for mocking and wanted features like that.

So I wrote https://github.com/dankinder/httpmock, which basically combines the two. If you just want a mock that accepts JSON and spits out JSON, it may be an easier way to go.

Mocking Http Request with HttpClient in Angular, In this post I will show how to mock http requests in unit tests using HttpClient. Instead we can use the new HttpClient test api to map mocked object responses to urls. constructor(private http: HttpClient) {} getLocations() { return this.http .​get('. assets/countries.json'); countryRequest.error(new  To fake it, just implement it. The message that goes in is the one that you sent HttpClient, and the response that comes out is up to you. For example, if I want to know that my code is dealing with a json body correctly, then just have the response return a json body that you expect.

Mocking HTTP request in Flutter - FlutterPub, fromJson(json.decode(response.body)); return itemModel; } }. 5. As always when it comes to making a HTTP request for a demo. We will be  To mock the results, click the “+” next to Servers. Create an API and under connected specs add your OpenAPI document. Finally, you’ll need to create a new rule, select your API, and add shared before/after scenarios. This ensures the traffic for the mock server is connected to your API.

MockServer, MockServer enables easy mocking of any system you integrate with via HTTP or HTTPS. return a "mock" response when a request matches an expectation all recorded requests can be converted into Java code or JSON expectations to  Sometimes I setup a stub HTTP server that returns canned responses based on pattern matching the request url, meaning you test real HTTP requests not mocks but to a localhost server. Using WireMock.net makes this really easy and runs fast enough to satisfy most of my unit testing needs.

Mocking External APIs in Python – Real Python, This call should return a JSON-serialized list of todo items. an HTTP request behind the scenes and then returns an HTTP response in the form of a Response​  However, the former is typically undesirable, and the latter requires switching to a separate mocking system for HTTP calls which may be less flexible or awkward in conjunction with other mocks. These extensions instead allow HttpClient to be mocked the same way as everything else using Moq without excessive boilerplate.

Comments
  • This is probably much easier (and more thorough) to test by mocking the service instead of the client. Take a look at httptest.Server.
  • Make a real request to a mock server. Take a look at how the stdlib does it and use net/http/httptest.
  • You can use ioutil.NopCloser(bytes.NewReader(body)) to set the response Body field.
  • Did some diving, httptest.Server particularly ts := httptest.NewServer(http.HandlerFunc(handler)) gives me ats.URL property that I can use to aim my test request at. Problem is my URL is generated on the method I'm testing. I can pass the hostname part of the URL to the method, problem now is my method prepends https:// but httptest.NewServer() doesnt work with https:// it looks like. I also tried httptest.NewTLSServer(). still no luck. any ideas? @JimB
  • If you need https, then you need httptest.NewTLSServer(). What didn't work?
  • http: TLS handshake error from 127.0.0.1:49876: remote error: tls: bad certificate
  • Look at the TLSServer example, you need to use the test client which has the cert loaded in the transport.