Member-only story
Creating Unit Tests Using Mock and Coverage Test in Golang — Learning Golang
INTRODUCTION
There are several things to consider when creating unit tests in Golang. For the unit test file, add the suffix _test.go
, and place the file in a folder where the code to be tested resides. When writing functions in the _test.go
file, add the prefix Test
, for example, TestCreateEmployee
.
In this unit test tutorial, we will use mocks. What is a mock? A mock is an implementation of an object that we define the output for. In certain conditions, mocks can be useful, such as minimizing execution time when a query process in a specific function takes a long time or if we don’t want to call the database.
For example, here we will create unit test files for Services and Controller using mock objects.
PREREQUISITE
Beforehand, import the mock
package and then we will create its mock files.
github.com/stretchr/testify
FOLDER STRUCTURE
-ProjectGO
--pkg
--src
--controller
--EmployeeController.go
--EmployeeController_test.go
--interfaces
--EmployeeRepository.go
--ServicesRepository.go
--mocks
--EmployeeRepository.go
--ServicesRepository.go
--models
--Employee.go
--Response.go
--repository…