Writing unit tests is always something really important, but it can be really long or complex. Sometimes, we have some code which can only be checked by reading logs.
So today, we will see how to adapt our code to resolve this issue and make easier to write your unit tests.
To make it happen, we will use a technique which is already known in the Golang Unit test universe, that is : create a variable to store the object or function we want to mock.
In every package, we will create a
log.go file which will contain the following code :
var logger = log.New(os.Stderr, "", log.LstdFlags)
Then, you will be able to use it like the other logger :
But where did this code came from?
This line of code comes from the
log package. It's the declaration of the
std variable which is used in the
log.Println function for example.
And as you can see, we just duplicate the declaration of this new logger instance, but we did it in our packages to be able later to replace it with our mock.
Now that we have those variables created, it will be really easy to mock them.
But first, we need to create the mock!
var ( buff bytes.Buffer MockLogger = log.New(&buff, "", log.LstdFlags) )
As you can see, the mock is almost the same than the logger. The only difference is the mock is using a buffer as output. This difference is quite huge because it will allow us to be able to read the printed logs.
So in your unit tests, you can declare the following line to replace your
logger by your mock.
logger = mocks.MockLogger
And then, you only have to retrieve the logs contained in the buffer with this
strings.Split(mocks.Buff.String(), "\n") to be able to do your lasts verifications.
Finally, overall it's quite simple but it let us do more than before!
I hope it will help you! 🍺