My experience with unit testing and mocks in Golang

Alex Popa
Alex Popa
Aug 26, 2017 · 2 min read

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.

The connection 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.

)

Alex Popa

Written by

Alex Popa

software developer, Not a gopher yet

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade