A Complete Guide to Database Testing with Practical Tips and Examples:
Computer applications are more complex these days with technologies like Android and also with lots of Smartphone apps. The more complex the front ends, the more intricate the back ends become.
So it is all the more important to learn about DB testing and be able to validate databases effectively to ensure security and quality databases.
In this tutorial, you will learn all about Data Testing – why, how and what to test.
The database is one of the inevitable parts of a software application.
It does not matter whether it is a web, desktop or mobile, client-server, peer to peer, enterprise or individual business; the database is required everywhere at the backend.
Similarly, whether it is healthcare, finance, leasing, retail, mailing application or controlling a spaceship; a database is always in action behind the scene.
As the complexity of application increases, the need for a stronger and secure database emerges. In the same way, for the applications with a high frequency of transactions (e.g. banking or finance application), the necessity of fully featured DB Tool is coupled.
Nowadays, we have big data which is large and complex that the traditional databases can’t handle them.
There are several database tools are available in the market e.g. MS-Access, MS SQL Server, SQL Server, Oracle, Oracle Financial, MySQL, PostgreSQL, DB2, Toad, Admirer, etc. These tools vary in cost, robustness, features, and security. Each of these has its own benefits and drawbacks.
What You Will Learn:
- Why Test Database?
- What to Test (Database Testing Checklist)
- How to Test the Database (Step-by-step Process)
Why Test Database?
Below, we will see why the following aspects of a DB should be validated:
#1) Data Mapping
In software systems, data often travels back and forth from the UI (user interface) to the backend DB and vice versa. So these are some aspects to watch for:
- Check whether the fields in the UI/frontend forms are mapped consistently with the corresponding fields in the DB table. Typically this mapping information is defined in the requirements documents.
- Whenever a certain action is performed in the front end of an application, a corresponding CRUD (Create, Retrieve, Update and Delete) action gets invoked at the back end. A tester will have to check if the right action is invoked and whether the invoked action in itself is successful or not.
#2) ACID properties validation
Atomicity, Consistency, Isolation, and Durability. Every transaction a DB performs has to adhere to these four properties.
- Atomicity means that a transaction either fails or passes. This means that even if a single part of the transaction fails- it means that the entire transaction has failed. Usually, this is called the “all-or-nothing” rule.
- Consistency: A transaction will always result in a valid state of the DB
- Isolation: If there are multiple transactions and they are executed all at once, the result/state of the DB should be the same as if they were executed one after the other.
- Durability: Once a transaction is done and committed, no external factors like power loss or crash should be able to change it
#3) Data integrity
For any of the CRUD operations, the updated and most recent values/status of shared data should appear on all the forms and screens. The value should not be updated on one screen and display an older value on another one.
When the application is under execution, the end user mainly utilizes the ‘CRUD’ operations facilitated by the DB Tool.
C: Create – When user ‘Save’ any new transaction, ‘Create’ operation is performed.
R: Retrieve – When user ‘Search’ or ‘View’ any saved transaction, ‘Retrieve’ operation is performed.
U: Update – When user ‘Edit’ or ‘Modify’ an existing record, the ‘Update’ operation of DB is performed.
D: Delete – When a user ‘Remove’ any record from the system, ‘Delete’ operation of DB is performed.
Any database operation performed by the end user is always one of the above four.
So devise your DB test cases in a way to include checking the data in all the places it appears to see if it is consistently the same.
#4) Business rule conformity
More complexity in databases means more complicated components like relational constraints, triggers, stored procedures, etc. So testers will have to come up with appropriate SQL queries in order to validate these complex objects.
What to Test (Database Testing Checklist)
When testing transactions it is important to make sure that they satisfy the ACID properties.
These are the statements commonly used:
- BEGIN TRANSACTION TRANSACTION#
- END TRANSACTION TRANSACTION#
The Rollback statement ensures that the database remains in a consistent state.
- ROLLBACK TRANSACTION#
After these statements are executed, use a Select to make sure the changes have been reflected.
- SELECT * FROM TABLENAME <tables which involve the transactions>
2) Database Schemas
A database schema is nothing more than a formal definition of how the data is going to be organized inside a DB. To test it:
- Identify the requirements based on which the database operates. Sample requirements:
- Primary keys to be created before any other fields are created.
- Foreign keys should be completely indexed for easy retrieval and search.
- Field names starting or ending with certain characters.
- Fields with a constraint that certain values can or cannot be inserted.
- Use one of the following methods according to the relevance:
- SQL Query DESC<table name> to validate the schema.
- Regular expressions for validating the names of the individual fields and their values
- Tools like SchemaCrawler
When a certain event takes places on a certain table, a piece of code (a trigger) can be auto-instructed to be executed.
For example, a new student joined a school. The student is taking 2 classes: math and science. The student is added to the “student table”. A trigger could add the student to the corresponding subject tables once he is added to the student table.
The common method to test is to execute the SQL query embedded in the trigger independently first and record the result. Follow this up with executing the trigger as a whole. Compare the results.
These are tested in both the black-box and white-box testing phases.
- White box testing: Stubs and drivers are used to insert or update or delete data that would result in the trigger being invoked. The basic idea is to just test the DB alone even before the integration with the front end (UI) is made.
- Black box testing:
a) Since the UI and DB, integration is now available; we can insert/delete/update data from the front end in a way that the trigger gets invoked. Following that, Select statements can be used to retrieve the DB data to see if the trigger was successful in performing the intended operation.
b) The second way to test this is to directly load the data that would invoke the trigger and see if it works as intended.
4) Stored Procedures
Stored procedures are more or less similar to user-defined functions. These can be invoked by Call Procedure/Execute Procedure statements and the output is usually in the form of result sets.
These are stored in the RDBMS and are available for applications.
These are also tested during:
- White box testing: Stubs are used to invoke the stored procedures and then the results are validated against the expected values.
- Black box testing: Perform an operation from the front end (UI) of the application and check for the execution of the stored procedure and its results.
5) Field constraints
The default value, unique value, and foreign key:
- Perform a front-end operation which exercises the database object condition
- Validate the results with a SQL Query.
Checking the default value for a certain field is quite simple. It is part of business rule validation. You can do it manually or you can use tools like QTP. Manually, you can perform an action that will add value other than the default value of the field from the front end and see if it results in an error.
The following is a sample VBScript code:
Function VBScriptRegularexpressionvlaidation(pattern , string_to_match) Set newregexp = new RegExp newregexp.Pattern = “<Default value as required by the business requirements>” newregexp.Ignorecase = True newregexp.Global = True VBScriptRegularexpressionvlaidation = newregexp.Test(string_to_match) End Function Msgbox VBScriptRegularexpressionvlaidation(pattern , string_to_match)
The result of the above code is True if the default value exists or False if it doesn’t.
Checking the unique value can be done exactly the way we did for the default values. Try entering values from the UI that will violate this rule and see if an error is displayed.
Automation VB script code can be:
Function VBScriptRegularexpressionvlaidation(pattern , string_to_match) Set newregexp = new RegExp newregexp.Pattern = “<Unique value as required by the business requirements>” newregexp.Ignorecase = True newregexp.Global = True VBScriptRegularexpressionvlaidation = newregexp.Test(string_to_match) End Function Msgbox VBScriptRegularexpressionvlaidation(pattern , string_to_match)
For the foreign key constraint validation use data loads that directly input data which violate the constraint and see if the application restricts them or not. Along with the back end data load, perform the front end UI operations too in a way that will violate the constraints and see if the relevant error is displayed.
Data Testing Activities
Database Tester Should Focus on Following Testing Activities:
1) Ensure data mapping:
Data mapping is one of the key aspects in the database and it should be tested rigorously by every software tester.
Make sure that the mapping between different forms or screens of AUT and its DB is not only accurate but also per the design documents (SRS/BRS) or code. Basically, you need to validate the mapping between every front-end field with its corresponding backend database field.
For all CRUD operations, verify that respective tables and records are updated when the user clicks ‘Save’, ‘Update’, ‘Search’ or ‘Delete’ from GUI of the application.
What you need to verify:
- Table mapping, column mapping, and data type mapping.
- Lookup data mapping.
- Correct CRUD operation is invoked for every user action at UI.
- CRUD operation is successful.
2) Ensure ACID Properties of Transactions:
ACID properties of DB Transactions refer to the ‘Atomicity’, ‘Consistency’, ‘Isolation’ and ‘Durability’. Proper testing of these four properties must be done during the database test activity. You need to verify that every single transaction satisfies the ACID properties of the database.
Let us take a simple example through below SQL code:
CREATE TABLE acidtest (A INTEGER, B INTEGER, CHECK (A + B = 100));
The acid test table will have two columns – A & B. There is an integrity constraint that the sum of values in A and B should always be 100.
Atomicity test will ensure any transaction performed on this table is all or none i.e. no records are updated if any step of the transaction is failed.
Consistency test will ensure that whenever the value in column A or B is updated, the sum always remains 100. It won’t allow insertion/deletion/update in A or B if the total sum is anything other than 100.
Isolation test will ensure that if two transactions are happening at the same time and trying to modify the data of the acidtest table, then these tractions are executing in isolation.
Durability test will ensure that once a transaction over this table has been committed, it will remain so, even in the event of power loss, crashes, or errors.
This area demands more rigorous, thorough and keen testing if your application is using the distributed database.
3) Ensure Data Integrity
Consider that different modules (i.e. screens or forms) of application use the same data in different ways and perform all the CRUD operations on the data.
In that case, make sure that the latest state of data is reflected everywhere. The system must show the updated and most recent values or the status of such shared data on all the forms and screens. This is called as Data Integrity.
Test cases for validating database data integrity:
- Check if all the triggers are in place to update reference table records.
- Check if any incorrect/invalid data exists in the major columns of each table.
- Try to insert wrong data in tables and observe if any failure occurs.
- Check what happens if you try to insert a child before inserting its parent (try to play with Primary and foreign keys).
- Test if any failure occurs if you delete a record that is still referenced by data in any other table.
- Check if replicated servers and databases are in sync.
4) Ensure the Accuracy of the implemented Business Rules:
Today, databases are not meant only to store the records. In fact, databases have been evolved into extremely powerful tools that provide ample support to the developers to implement the business logic at the DB level.
Some simple examples of powerful features are ‘Referential Integrity’, relational constraints, triggers, and stored procedures.
So, using these and many other features offered by DBs, developers implement the business logic at the DB level. The tester must ensure that the implemented business logic is correct and works accurately.
Above points describe the four most important ‘What To’ of testing DB. Now, let’s move on to ‘How To’ part.
How to Test the Database (Step-by-step Process)
The general test process testing database is not very different from any other application.
The following are the core steps:
Step #1) Prepare the environment
Step #2) Run a test
Step #3) Check test result
Step #4) Validate according to the expected results
Step #5) Report the findings to the respective stakeholders
Usually, SQL queries are used to develop the tests. The most commonly used command is “Select”.
Select * from <tablename> where <condition>
Apart from Select, SQL has 3 important types of commands:
- DDL: Data definition language
- DML: Data manipulation language
- DCL: Data control language
Let us see the syntax for the most commonly used statements.
Data Definition language Uses CREATE, ALTER, RENAME, DROP and TRUNCATE to handle tables (and indexes).
Data Manipulation language Includes statements to add, update and delete records.
Data control language: Deals with giving authorization to users for manipulation and access to the data. Grant and Revoke are the two statements used.
On <table name>
To <user id1, user id2…useridn>;
on <table name>
from<user id1, user id2…useridn>;
Some Practical Tips
#1. Write queries yourself:
To test the database accurately, the tester should have very good knowledge of SQL and DML (Data Manipulation Language) statements. The tester should also know the internal DB structure of AUT.
You can combine GUI and data verification in respective tables for better coverage. If you are using SQL server then you can make use of SQL Query Analyzer for writing queries, executing them and retrieving results.
This is the best and robust way of testing a database when the application is of a small or medium level of complexity.
If the application is very complex then it may be hard or impossible for the tester to write all the required SQL queries. For complex queries, you take help from the developer. I always recommend this method as it gives you confidence in testing and also enhances your SQL skills.
#2. Observe the data in each table:
You can perform data verification using the results of CRUD operations. This can be done manually by using application UI when you know the database integration. But this can be a tedious and cumbersome task when there is huge data in different database tables.
For manual data testing, the database tester must possess a good knowledge of database table structure.
#3. Get queries from the developers:
This is the simplest way to test the database. Perform any CRUD operation from GUI and verify its impacts by executing the respective SQL queries obtained from the developer. It neither requires a good knowledge of SQL nor requires a good knowledge of the application’s DB structure.
But this method needs to be used cautiously. What if the query given by the developer is semantically wrong or does not fulfill the user’s requirement correctly? The process will simply fail to validate data.
#4. Make use of Database automation testing tools:
There are several tools available for data testing process. You should choose the correct tool as per your needs and make the best use of it.
With all these features, factors and processes to test on a database, there is an increasing demand on the testers to be technically proficient in the key database concepts. Despite some of the negative beliefs that testing a database creates new bottlenecks and is a lot of additional expenditure – this is a realm of testing that is attracting significant attention and demand.
I hope this tutorial has helped to focus on why that is so and has also provided you with the basic details of what goes into testing a database.
Please let us know your feedback and also share your personal experiences if you are working on DB testing.