Member-only story
Unit Testing a GORM Application With a Real DB Server
Unit testing with a DB server running in docker is a much better choice than Sqlmock, usually
About two years ago, I wrote an article discussing how to test a GORM application with Sqlmock.
Time flies, and I realize that most developers do not adopt this approach (at least on my team). Writing a test case using Sqlmock is too complex to get started.
The core issue is that you need to write up the whole SQL snippet manually, then compare it with the output from GORM. This workload is already much more than writing the codes to be tested. After all, the reason we use GORM is to avoid writing raw SQL manually.
We need to find a better way.
Improve Unit Testing Process
In general, testing DB application is hard. The main reason is the database server itself.
- If the dev team shares a remote database server, then data conflict is inevitable.
- If we create accounts for every developer on this database server, then unit tests should be run with different accounts. And someone needs to maintain these accounts.
- If we demand every developer install and set up a database server on their local workstation, we increase the difficulty of setting up a development environment.
Seems there’s no answer is good enough. But if we could run the database server locally with docker and integrate the test case with docker, that would be perfect.
Image process below:
- Start a database server with docker before each test suite. open a GORM connection to this server
- Before every test case runs, clear data in the database and re-create tables if needed
- Run all test cases
- Stop the database server after test suite execution

In theory, we could control the docker daemon with a command line. But with the help of dockertest, this target could be…