In my last post I had promised I will discuss testing techniques. Today I will discuss testing database manipulation if it iss part of a class and you are doing a unit testing of this class.
When you test a business logic, you test if the computation done inside a class through some method, the computation is correct. For example, if you need to compute correct interest rate for a fixed deposit in a bank in your class using a method then you store values for the principal amount and given interest rate and then do your computation and find out the accrued amount after the interest calculation is done.
If you are testing this class and its method then you will give various values for principal amount and interest rate and find out if the class is doing correct computation and giving you correct results. Suppose the interest rate to be calculated comes from values stored in a database table then what kind of challenges you will face and what kind of strategies you will have to make to overcome those challenges?
If you ever have done a database testing stuff for your classes then you must be aware of the challenges. For novice testers, let me stress that there are indeed many stiff challenges in this task. Some of these challenges include:
- To manipulate a database, you first need to have a connection and only then you can do any database manipulation. This means that you will first need to do an integration test in form of testing the connection with a database and only then you can perform a unit test.
- Database is a separate entity and not part of the software system you are testing. This fact again implies that what you are going to perform is actually not a unit test but some sort of an extended test. When you are testing business logic for your class, you are also testing the database structure at the same time.
- Databases carry a permanent data structure and thus have a different behavior compared to the software component your class belongs to. During execution, data inside a data structure of the software component (e.g. the data structure of the class itself) experience value changes. But after execution, data inside these data structures get reset. For example, suppose you have a variable ‘a’ in your method and you assign it a value 5 during execution. After the source code execution completes, value of this variable will become NULL as the object which was carrying this variable will be destroyed. But if you change value of a field in a database during testing then this change will be permanent. For example if you changed first name of an employee from ‘Alan’ to ‘Keith’ in a database table then this change is permanent. Now if you query the database to find first name as ‘Alan’ then you will get an error because the name is ‘Keith’ and not ‘Alan’. This fact has a profound impact on the way you do unit testing.
In my next post I will show you how to tackle these challenges.