How to mock a no response from server with Gin Golang

38 views Asked by At

I'm mocking a server for testing my application. I built the mocked server with Golang and Gin. It works well for successful cases.

But one of the cases I want to test is how the application behaves when there is no response from the server. I want that when the application sends a request with a specific value, the mocked server shall not answer. But I did not manage to achieve that with Gin.

I tried that the Gin handler function shall not set the context, but Gin still sends an empty 200 OK. A router.GET without handler also replies with an empty 200OK. I checked the extensive Gin documentation, but I could not find an answer.

How can I simulate a server or network error where the response is never received?

1

There are 1 answers

0
dustinevan On

When a server returns nothing, there are two situations (that I know of)

  1. The connection is open, but no response has been returned -- A Timeout
  2. The connection closes, or is reset by the server -- A Network Error or Connection Reset

From the question it sounds like we're looking to model #2.

For testing purposes, a way to simulate a connection reset is by returning an error from the http.RoundTripper internal to the http.Client used in the test. Note that this doesn't involve Gin. The test is to see how some client reacts to a connection reset by the server.

Internal to an http.Client is an http.RoundTripper which is an interface which requires the method:

RoundTrip(*Request) (*Response, error)

According to the docs:

RoundTrip must return err == nil if it obtained
a response, regardless of the response's HTTP status code.
A non-nil err should be reserved for failure to obtain a
response.

Here's an example of how to do this:

type connectionResetTransport struct {}

func (c *connectionResetTransport) RoundTrip(req *http.Request) (*http.Response, error) {
    return nil, errors.New("connection reset")
}

// usage
connectionResetClient := http.Client{
    Transport: &connectionResetTransport{},
}

connectionResetClient.Get("http://localhost:8080")
// or use connectionResetClient as the http.Client in whatever system you're trying to test