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.



Sakib Sami

Senior Software Engineer @ Twilio | Entrepreneur | Tech Ninja