Unit Testing in Go

It is vital to test any new code we add if we want to avoid releasing buggy code and then deal with the headache of debugging and fixing it in a time crunch. Some of the issues this can lead to can be disastrous, and if they result in data loss, it could even lead to losing customers.

There are many kinds of tests we can use to cover our app. One of them is unit tests.

What is unit testing?

Unit tests are generally the first kind of test written for code. They are great for enabling test-driven development (TDD).

Some of the things that make unit tests great are:

  • Unit tests are written at a very granular level, mostly per function.

  • They help us make sure that the code is behaving exactly how we want.

  • They can be run without a lot of supporting code.

  • They are super fast. Most unit tests can complete within a few seconds.

  • Unit tests help catch bugs early on in the development process.

  • They also help avoid regression due to any new changes or refactoring.

Unit testing in Go

Go recognizes the importance of unit testing. Therefore, it offers a built-in package called testing, which is super easy to use and doesn't take long to learn.

Let's take a simple example to see how it works.

Unit testing with a simple example

Let's try to unit test the code snippet given below. In the code:

  • We have a function AddTwoNumbers in line 11, which takes two integers as inputs and returns their sum.

  • We call the AddTwoNumbers function from the main function in line 7.

  • The result is printed in line 8.

Go ahead and click the “Run” button below to run this program!

Get hands-on with 1200+ tech skills courses.