How to Create a Data-driven Test
Intro
There are times when you run across functionality you want to test repeatedly with various inputs to see how the system behaves. We're going to go over a way to do this that will take some of the burden out of the process.
Sometimes performing these tests are because you want to test the expected outcomes. Other times, because you want to see if the system breaks in an odd way. But, wiring up all these permutations into a set of automated tests can be burdensome and rife with copied code, which can make it hard to maintain over time.
A Solution
Enter Data-driven Testing.
By storing your desired inputs and expected outcomes in a central repository of some kind (e.g. a comma separated file, database, etc.) you can easily wire up tests to use each of them instead of writing numerous tests and hard-coding these values directly in your test code.
Example
Let's test a login form on a website (e.g., with this example on the-internet).
First, we create a file to store the test inputs and expected outputs in. In this case, a CSV (comma-separated value)
file called user_data.csv, like so:
account_type,username,password,notification_message
bad_password,tomsmith,badPassword,Your password is invalid!
bad_username,badUsername,SuperSecretPassword!,Your username is invalid!
standard_user,tomsmith,SuperSecretPassword!,You logged into a secure area!
Then we write a single test that logs in and checks the notification message, and we use the data-driven features of each test framework to run it once for each row in the file.
We also need a helper to obtain the notification text from the page. It waits for the notification to be displayed
and returns its text. The notification includes a close button (×) after the message, so we check that the text
starts with the message we expect.
Expected Behavior
For each entry in the CSV file:
- Open the browser
- Load the login page
- Submit the login form with user data
- Grab the notification message and assert it against the expected value
- Close the browser
Summary
By storing data in a central repository to use for your tests and using Data-driven testing, you can simplify running repeated tests with various inputs.
Happy Testing!