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 API interface
.
Implementation
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
|
|
Unit Test
|
|
Because we only change the http.Client
, our FetchPostByID func
is tested as it is except for this line:
|
|
Because the 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!