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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

A general use guide for Pyinstaller

System.currentTimeMillis() vs SystemClock.elapsedRealtime()

How to Re-Order WordPress Posts By Custom Field?

SkillWallet presents: Identity Spring

How to do a Program Analysis?

DynaMediaPackager — A Library for Dynamic Media Packaging based on Shaka Packager

What is NHibernate and how is it different from Entity Framework

Cloud boxing…Getting an Ubuntu Box with AWS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bismo Baruno

Bismo Baruno

Software Engineer | Traveler | Guitarist | J-Lovers

More from Medium

gRPC: JWT interceptor on gRPC

Use pprof to view go program stack traces

Small Go package style (part 1)

Hacking sum types with Go generics