Lately, at work, I’ve been assigned the task to test the backend: queries, utils and rest API programmatically.
At first I was totally lost - searching for any examples on the internet (or GPT) didn’t help and I didn’t want to use a mock DB for this purpose
Thankfully, the senior developer in our team gave me clear pointers on where to begin (Thank you, Jungsu!)
So here are some of my notes:
Streamlined Golang Backend Testing Using DBeaver and Docker: A Step-by-Step Guide
Step 1: Installing DBeaver, Docker and PostgreSQL
To manage and visualize your database during testing, install DBeaver.
Note:
THIS IS WAYYYY BETTER THAN USING A MOCK DB
Step 2: Creating a Separate Database:
If you need a separate database instance, you can create one using Docker. Run the following command to set up a PostgreSQL database with a specific name, password, and port:
docker container run \ --name alpha_db \ -e POSTGRES_PASSWORD=mysecretpassword \ -e PGDATA=/var/lib/postgresql/data/pgdata \ -e POSTGRES_USER=postgres \ -v /Users/sansverse/Documents/docker-related/alpha:/var/lib/postgresql/data \ -p 5433:5432 \ -d postgres:15
Step 3: Preparing for Testing
- Apply Migrations on Startup:
Integrate migration into your code to automatically apply database changes during startup. This ensures that your database schema is up-to-date before testing begins:
- Loading
.env
File, which may look like this:
SERVER_HOST=10.10.1.41 SERVER_PORT=3001 DB_HOST=10.10.1.41 DB_PORT=5433 DB_USER=postgres DB_PASSWORD=mysecretpassword DB_NAME=postgres DB_SSL_MODE=disable
func init() { err := godotenv.Load("./../../.env") if err != nil { logrus.Fatalln("Error loading .env file") } }
Step 4: Running Tests
- Run All Tests:
Execute all your tests using the following command:
$ go test -v ./...
- Running Specific Tests:
If you want to run specific tests, use the
-run
flag along with a regular expression to filter tests:$ go test -v -run <test_name_regex>
Conclusion
Efficient testing is essential for maintaining the quality of your Golang applications. By integrating DBeaver and Docker into your testing process, you can manage databases effortlessly and ensure that your backend is robust and reliable.