Unit Test (HTTP Request) in Golang

Photo by pixabay.com

Hi everyone! With me, again and again, to share some experience, thought, or opinion about technology-related with the software engineering field. After delivering story about mocking data on SQL and Redis, in this section, I want to share how to mock our HTTP request code for Unit Test purpose.

Have you been write some code for communicating with external services? Especially using REST? Nowadays, communicating with external services isn’t new things for us. We have a lot of services that help us to improve our services. For the example, sending email, push notification, SMS, getting location data, etc.

But, have you imagine how to do Unit Test for those external services? Since, when we talk about Unit Test, it should be isolated from external services. And the answer is, mock the HTTP response! I found this great example and inspired to write this story.

We will try to create a simple code for communicating with this API http://dummy.restapiexample.com/

The endpoint that we will try is getting employees. With method GET and api/v1/employees path.

I also create helper for simplify the HTTP request and the HTTP mock. If you want to see the detail about the helpers, you can visit my repository on github.

Next, create the HTTP request function. We should wrapped it with struct for achieve mocking the http server url. With my helper, call another services will be simpler. Just need to set the options like timeout, url, method, etc.

Next, the test file. With my helpers, we can easily mock the request. Just need to define the path, http status code and the response.

Okay, after both files are ready, try to run the test with this command

go test ./... -cover
Picture Test Passed

Yeah, we passed the test! Also getting 100% code coverage!

Hope you enjoy it, I’m happy if this article useful for you! Happy testing!

Thank you!

Software Engineer | Traveler | Guitarist | J-Lovers