Unit testing in Go using Mockery

Jcdan
2 min readDec 12, 2021

Intro

In modern software development, unit testing is a necessity for any serious programming project.

One of the challenges when writing unit tests in Go is when our code interacts with files, websites, or any third-party service.

Mockery is a library that helps us to deal with such problems.

In this tutorial, we will go through the concept using a simple example.

Files structure

In our example, we will want to mock a function that reads a file.

In our test, we don’t want to read the actual file.

First, let's take a high-level view looking at the file structure:

fileconnector.go -> this is the structure that will let us read from a file.

filesystem.go -> this is the high-level structure that will use the fileconnector.

filesystem_test.go -> the unit test file for filesystem.go

Code

Now let dive into the code starting with fileconnector.go

As you can see, all that fileconnector does is ReadFrom a fi.e

The fileConnector struct implements the FileConnector interface.

The NewFileConnector() function, return type is the interface but it actually return a fileConnector struct.

Now lets take a look at filesystem.go

Installing and using Mockery

First, install mockery:

go get github.com/vektra/mockery/v2/…/

Now run mockery in the same directory as the filesystem.go file.

mockery --all

You should now have a file named FileConnector.go in the folder mocks.

Let’s look at this file content:

A few notes:

  • All the interface types found in our code are now mocked. As you can see, the FileConnector structure of this file implements our interface.
  • The file has its own package, named mocks.
  • Never edit directly this file.
  • If you change the code, regenerate the mocks with the command stated above.

Using the generated mock

Now lets look at the test file:

The important line is:

connectorMock.On("ReadFromFile",fileToRead).Return([]byte("hello"),nil)

This defines the behavior we want the mock to have. Here we basically say

For the method ReadFromFile, when receiving the argument fileToRead (which is defined as “mockFileToread.txt”), return the values:

 []byte(“hello”), nil

That is it. You now know how to use mockery to mock your interface and how to use it in unit tests!

All the code for this tutorial is open source and on my public repo.

--

--

Jcdan

Experience software developer in a quest to democratize software development. More here: https://www.linkedin.com/in/jcdansereau