Database Mocking
Learn how to mock a database client for unit tests, why it shouldn't be mocked manually, and which packages to use to mock it out.
Databases are one of the fundamental parts of almost every program. Sooner or later, we have to store the data used by our application somewhere. That’s where databases come in. However, they’re also one of the most challenging parts of unit testing.
Usually, mocking a database isn’t something we can manually do. It’s very time-consuming and challenging to mock out all of the features a database client can provide. Here, the preferred approach is to rely on third-party packages. In our case, we’ll depend on the package go-sqlmock
. This is by far the most used package that implements sql/driver
. This package will assist us with the following:
- Quickly mock the behavior of the database. It permits us to test also database errors that we might face.
- Respecting the TDD approach that states we’ve to write tests first without worrying about if the database will be a PostgreSQL or a MySQL implementation.
Blog application
To better understand how to achieve unit tests without interacting with the actual database, we use a practical example. The application is a blog management application that allows us to accomplish two tasks:
- Insert a new blog post on the platform.
- Retrieve the blog posts already stored.
Let’s visualize the various component of our application:
Get hands-on with 1200+ tech skills courses.