My experience with unit testing and mocks in Golang

Recently I started learning and working on a web project using the Go Language.It’s been a few exciting and difficult weeks since i decided to try to learn and code in Golang.One of the challenges I’ve encountered was unit testing and most especially injecting mocks in my structs.
In the following example, I used the testify package that provides assertions functions that help write better unit tests. To write a test in Go ,create a file with a name ending in _test.go that contains functions named TestXXX with signature func (t *testing.T).

To inject mocks in my struct, I used Interfaces and Compostion.Basically i defined an interface and in my unit tests i provided a mock implementation for that interface.


This is the use of compositon, here the connection interface is embedded in the API struct.
So now providing a mock implementation of the connection interface I could test in isolation the api.

mock.Called tells the mock object that a method has been called, and gets an array of arguments to return.
In the mocked function there can be provided any form of behaviour and thus testing the way your code should handle different returns from the embedded interface.
That’s it , my simple mock injection using testify package, so you can easily test your code in isolation.
