In my previous post we had considered the challenges of unit testing where databases are involved. In this post we will see how to overcome those challenges.
The first challenge is about the fact that a database is an external entity. You can only manipulate a database if you have a connection with the databaase. For any reason if the connection with the database gets broken then you can not do anything with the database. This means the first thing you need to do is to test if a connection with the database is available and it is working. This kind of testing is essentially an integration testing and not a unit testing. Once your database connection test passes then you can write a query which will do some data manipulation in the database. This query will actually change data in the database. On a software project, lot of database testing is performed. This may result in lots of testing data will be created and manipulated in the database. This is not a good practice.
A better approach will be to create a record containing test data in the database and then delete this test data once your testing is complete.
When you follow these principles then you can do your unit teesting with database comfortably.