I am learning a bit about test coverage in Golang and having some interesting issues.
I have a fair basic code for calling an API and executing the http.Client.Do(request). After the execution I check for error and return it if its found.
resp, err := Client.Do(request)
if err != nil {
return response, err
}
Also, I have added tests for it. Where I am mocking the Do function and returning an error.
mocks.DoFunc = func(*http.Request) (*http.Response, error) {
return nil, errors.New("hello world")
}
When I log the if err != nil condition, I can see that my code is running and being catch by this simple evaluation.
My problem starts when executing go tool cover -html=coverage.out. The output indicates that this condition is not covered.
SO, why I can check for it when logging and go tool is not detecting it, what am I missing?
CodePudding user response:
Ok. Not sure, but worked.
It seems that the Test Order is really important on TestCoverage, creating tests that evaluate from the least to first if err != nil did the trick.
My code do a simple fetch an API:
- Create a Response object
- Format the URL ID
- Creates a Http.NewREquest
- Evaluates NewRequest err
- Executes http.Client.Do(request)
- Evaluates Do err
- And So on and on...
...
response := &Response{}
url := fmt.Sprintf(pokeapiURLById, pokeId)
request, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
resp, err := Client.Do(request)
if err != nil {
return nil, err
}
...
Tests where created in the following order.
func TestFetchById_WhenHttpNewRequestFails(t *testing.T) {...
func TestFetchById_WhenClientDoFails(t *testing.T) {...
First, I test the NewRequest err and then Client.Do(req) err. And this way I got 80% of test coverage....
When I changed the order of my test methods:
func TestFetchById_WhenClientDoFails(t *testing.T) {...
func TestFetchById_WhenHttpNewRequestFails(t *testing.T) {...
I Have 100% of test coverage. I do not know if its an issue or it supposed to be like that... But, now, it's working good.
