This article has been updated. I recommend you to read the updated article.
This blog post code is running on go1.16.2
API Interface to be tested
We can simply mock the
API interface FetchPostByID function result in our unit test by creating a mock implementation of the
API interface like this:
API Mock implementation
But by doing that, it doesn’t increase the test coverage and it will skip the rest of the code inside the
FetchPostByID real implementation.
So we’re gonna make the testable real implementation first of the
To mock only the HTTP Call, we need to create http.Client mock implementation. the
real http.Client have
Do function that executed whenever we want to do HTTP call. So we need to mock the
Do function. Because
http.Client doesn’t have any interface implemented by it, we need to create one.
HTTP Client Mock
API Implementation Struct
Because we only change the
FetchPostByID func is tested as it is except for this line:
a.c.Do is already adjusted with our mock
DoFunc inside the unit test, the
a.c.Do behavior will be changed according to this line:
Let’s run the test
Thank you for reading!