Software testing

Using a Separate Database for Every Unit Test

Test one functionality at a time

Anas Anjaria
2 min readSep 11, 2022
Using a Separate Database for Every Unit Test
Photo by David Travis on Unsplash

Unit testing means

Testing one functionality at a time.

Unit testing is crucial in my opinion. It not only allows us to test specific functionality but also enables us to understand the given functionality.

Therefore, it’s crucial to give the same importance to unit tests as to other programming practices.

Over time I have learned some good practices and I am sharing them in this series.

Using a separate database for every test

It’s about testing DAO layers where we populate test data into a database (DB) to test some functionality.

Please note that each unit test will have its own DB with test data.

So here is a pseudo code.

Pseudocode

1. Start unit test
2. Create a database
3. Populate test data
4. Test functionality
5. Tear down the created database.

Why should I do that?

  • To have deterministic testing irrespective of the order of test execution.
  • Each test is isolated and enables us to maintain it easily since there are no dependencies between unit tests.

Tip for creating a separate Database for every test

Use database migrations [1]

So the above pseudo code would be as follows.

Pseudocode

1. Start unit test
2. Create a database and apply migrations
3. Populate test data
4. Test functionality
5. Tear down the created database.

As we want to keep our testing close to the production system, therefore, I would recommend using dedicated users in the unit test.

  • (Application) user (only for CRUD operation)
  • Admin user (only for creating DB)
  • Migration user (only for applying migrations)

Resources

[1] https://medium.com/@anasanjaria/how-to-use-database-migrations-f2ee53d4b643

Thanks for reading.

If you have any questions, please use the comments section. I will be happy to answer them.

If you enjoyed this post, you might also enjoy my following series.

Programming

20 stories
Lessons I Learned as a Code Reviewer
From Chaos to Clarity: Organizing Your Code
Replication conflict — High-level overview

Site reliability engineering

6 stories
Essential metrics to monitor continuous archiving & point-in-time recovery
Monitor Your System — Practical Guide. Site reliability engineering
High level overview of collecting Postgres metrics using custom query

--

--

Anas Anjaria

I simplify software engineering by sharing practical lessons and insights. My goal is to help early-career developers grow into proficient Software Engineers.