Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock http.Client Do method

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

like image 354
quentino Avatar asked Apr 05 '17 20:04

quentino


People also ask

Can you mock HttpClient?

HttpClient's extensibility lies in the HttpMessageHandler passed to the constructor. Its intent is to allow platform specific implementations, but you can also mock it. There's no need to create a decorator wrapper for HttpClient.

What is mock method?

Mocking means creating a fake version of an external or internal service that can stand in for the real one, helping your tests run more quickly and more reliably. When your implementation interacts with an object's properties, rather than its function or behavior, a mock can be used.

What is NSubstitute C#?

NSubstitute is a friendly substitute for . NET mocking libraries. It has a simple, succinct syntax to help developers write clearer tests. NSubstitute is designed for Arrange-Act-Assert (AAA) testing and with Test Driven Development (TDD) in mind. NSubstitute.Analyzers.CSharp.

What is mock testing C#?

Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.


Video Answer


1 Answers

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.

like image 191
Gavin Avatar answered Oct 05 '22 15:10

Gavin