How to Unit Test a GORM Application With Sqlmock

Tips and tricks to work with GROM and PostgreSQL

Photo by Nicolas Thomas on Unsplash.

Unit testing DB-interactive codes is not easy. It becomes harder when an ORM library like GORM is involved.

Theoretically, we could mock all the interfaces of database/sql/driver (such as Conn and Driver) with the great mock tool GoMock. However, we still need a lot of manual work to complete this kind of testing even with the help of GoMock.

The good news is Sqlmock could solve the aforementioned problem. As declared by its official website, it’s an “Sql mock driver for golang to test database interactions.”

This article will show you how to unit test a simple blog application with Sqlmock. The application is backed with PostgreSQL and uses GORM to simplify O-R mapping.

We’ll write test cases with the BDD testing framework Ginkgo, but you can change to any other testing library you prefer.

Our blog application will contain a blog data model and a repository struct to handle DB operations.