125

Unit test for Gorm application with go-sqlmock

 2 years ago
source link: https://tienbm90.medium.com/unit-test-for-gorm-application-with-go-sqlmock-ecb5c369e570
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Unit test for Gorm application with go-sqlmock

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK