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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With