Writing Test Cases in Golang
Unit Testing :- What ? Why ? How ? (in Golang)
Unit testing is a software testing method where individual components of software are tested. Developers write unit tests for their code to make sure that the code works correctly. This helps to detect and protect against bugs in the future. It also helps in ensuring that the software functions as intended.
Writing new features and building frameworks is pretty exciting for a software developer but we would all concur that we do not appreciate writing unit tests (at least in the initial days as a software developer :D).
This blog will focus on making it easy for you to write unit tests.
Unit Testing in Golang
Unit testing in Go is easy. There is a built-in package for writing unit tests called
Create a file called
Create a test file by adding
_test to the corresponding file.
So our file would be called
This test case will pass only when the function
RemoveNonAlphaNumeric removes all the non alpha numeric characters from the string.
If some developer makes changes to the
RemoveNonAlphaNumeric function which breaks causes some undesirable alterations to it then the Test Case would fail. In this way, unit test cases prevent bugs from creeping in to production.
Test ≠ Unit Test if :-
It interacts with a database
It performs some form of network communication
It can’t run in parallel with any other unit tests
However we cannot prevent external calls in our code.
So then how do we write unit tests for these functions ?
We use Mocks.
How to perform testing using mocks ?
Let’s understand this using an example.
Consider we are using an external package called
database which is defined as follows :-
Now let’s create another package called
user that has a dependency on the
Now let’s try to create test cases for it
As you can see that the
RegisterUser function makes call to
database.FetchUserID but ideally a unit test case should not make external calls.
This can be fixed using Mocks.
First create an interface for database package call it
Now modify user.go
As you can see that we passed the interface of the database to the RegisterUser function.
We can now do a mock implementation on the interface
In this way, we write test cases for functions that make external calls.
PS :- If you are facing problems in writing mocks, there is a high probability that you haven’t structured the interface properly.
There is a small problem in this approach. Can you find it out ? Let me know in the comments section.
Hint :- It has something to do with UserID