Golang: How to mock test

Sakib Sami
3 min readJul 10, 2021

Hello folks, though we are passing a critical time due to the COVID-19 pandemic I hope you all are well and safe.

In software development one of the major & critical parts is software testing. Testing can vary in type. Today you will learn how you can implement mock testing in your Golang project.

What is the mock test?

Mock testing is an approach to unit testing that lets you make assertions about how the code under test is interacting with other system modules. In mock testing, the dependencies are replaced with objects that simulate the behaviour of the real ones. Mainly in mock testing, we simulate the behaviour of a third-party service, we are using in our project.

How to mock?

In this project, I will use https://github.com/golang/mock library to implement mock testing. If you want you can use any other library as well. Now create a project and execute the following to include the libraries in your project,

go get github.com/golang/mock/gomock go get github.com/golang/mock/mockgen go get github.com/stretchr/testify

github.com/stretchr/testify is a test assertion library.

Let's say we have two micro-services mockingjay and user . In mockingjay we have integration with user service, so we will simulate the behaviour the of user service in mockingjay service.

Let’s have an interface defining the behaviour of user service.

type UserService interface { CreateUser(name, email string) (*User, error) UpdateUser(ID, name, email string) (*User, error) GetUser(ID string) (*User, error) DeleteUser(ID string) error }

In above interface we have defined the CRUD operations of user service.

type User struct { ID string Name string Email string }

Now the below code will generate mocks based on these definitions,

//go:generate mockgen -source=user_service.go -destination mocks/mock_user_service.go -package mocks UserService

Below is the project structure,

Now execute the below command to generate mocks,

go generate ./...



Sakib Sami

Senior Software Engineer @ Twilio | Entrepreneur | Tech Ninja