I'm trying to find a solution to write test and mock HTTP response. In my function where I accept interface:
type HttpClient interface {
Do(req *http.Request) (*http.Response, error)
}
I makes http get request with base auth
func GetOverview(client HttpClient, overview *Overview) (*Overview, error) {
request, err := http.NewRequest("GET", fmt.Sprintf("%s:%s/api/overview", overview.Config.Url, overview.Config.Port), nil)
if (err != nil) {
log.Println(err)
}
request.SetBasicAuth(overview.Config.User, overview.Config.Password)
resp, err := client.Do(request)
How can I mock this HttpClient? I'm looking for mock library, for instance: https://github.com/h2non/gock but there is only mock for Get and Post
Maybe I should do it in a different way. I'll be grateful for advice
Any struct with a method matching the signature you have in your interface will implement the interface. For example, you could create a struct ClientMock
type ClientMock struct {
}
with the method
func (c *ClientMock) Do(req *http.Request) (*http.Response, error) {
return &http.Response{}, nil
}
You could then inject this ClientMock
struct into your GetOverview
func. Here's an example in the Go Playground.