Unit test for Gorm application with go-sqlmock

DPBD90
2 min readSep 10, 2020

UNIT TESTING is a type of software testing where individual units or components of a software are tested. The purpose is to validate that each unit of the software code performs as expected. Unit Testing is done during the development (coding phase) of an application by the developers. Unit Tests isolate a section of code and verify its correctness. A unit may be an individual function, method, procedure, module, or object.

Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies. In mocking, the dependencies are replaced by closely controlled replacements objects that simulate the behavior of the real ones.

In this tutorial, we’ll be discussing how to create unit test for gorm code with go-sqlmock. This tutorial will show you how to unit test a simple application with Sqlmock. The application is backed with MySQL and uses GORM to access database.

Define GORM Data Model and Repository

Let’s define the data model and the repository struct first:

product.go

product_repository.go

Go-sqlmock

Before create new unit test with sqlmock, we must know how actual query will be matched with expected query on test. Sqlmock provides two types of Querymatcher includes:

  1. QueryMatcherRegexp: which uses expected SQL string as a regular expression to match incoming query string. By default, query matcher is sqlmock.QueryMatcherRegexp. and to create QueryMatcherRegexp use the following:
db, mock, err := sqlmock.New()

2. QueryMatcherEqual: which will do a full case sensitive match. And In order to customize the QueryMatcher with QueryMatcherEqual , use the following:

db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))

Testing with QueryMatcherRegexp

Testing with QueryMatcherEqual

Test INSERT statement

For the complete source code, please visit its repository.

--

--

DPBD90

I'm an engineer. I love to work on data and open-source systems.