Our great sponsors
-
dockertest
Write better integration tests! Dockertest helps you boot up ephermal docker images for your Go tests with minimal work.
-
InfluxDB
Power Real-Time Data Analytics at Scale. Get real-time insights from all types of time series data with InfluxDB. Ingest, query, and analyze billions of data points in real-time with unbounded cardinality.
-
WorkOS
The modern identity platform for B2B SaaS. The APIs are flexible and easy-to-use, supporting authentication, user identity, and complex enterprise features like SSO and SCIM provisioning.
I use https://github.com/DATA-DOG/go-sqlmock for unit testing my data layer code. Most of the times, these tests help me to find errors whenever I do a refactor on the data layer, so I consider it a good safety net
I use github.com/ory/dockertest to setup the database in a Docker container when the tests run, so a simple go test . works perfectly no extra steps needed (besides having Docker running in the background, most CI/CD envs should have it already).
The same idea was used to generate and mock sql queries in keploy - https://github.com/keploy/go-sdk/tree/main/integrations/ksql
We even use bats to run full integration tests with other systems at the end.
Let's look at some real codebase for an example on how to write database tests without mocking. The source code for the Go package discovery site(https://pkg.go.dev/) is available at[1] That site uses postgres as its primary database[2]. The database package has a method called GetLatestInfo[3] that fetches the latest versions of a module. That method is called from the frontend http handlers[4] via an interface[5] When it comes to testing that frontend handler, you would expect the tests to use a mock implementation of that interface method. But that's not what they do, instead they use a real postgres database in the test[6].