Software testing
Using a Separate Database for Every Unit Test
Test one functionality at a time
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.
![Replication conflict — High-level overview](https://miro.medium.com/v2/resize:fill:388:388/1*BQngBRBh5EnK_29T6UD76A.png)
![Essential metrics to monitor continuous archiving & point-in-time recovery](https://miro.medium.com/v2/resize:fill:388:388/1*IE5FIi4NRZ7iIGYk6siJzw.png)
![High level overview of collecting Postgres metrics using custom query](https://miro.medium.com/v2/resize:fill:388:388/1*wGBWHb2-SVt6p9m_GF4XTg.png)
Want to connect?
https://anasanjaria.bio.link/Follow: Facebook | LinkedIn