Dynamic data in Selenium

Use a simple Java class to provide data for your test scripts.

Test scripts feed different sets of data into the application being tested in order to test different execution paths of the application. While you could manually change the data explicitly in the test script, it is better to provide the data dynamically from an "external" data source.

In this example we use a simple two-dimensional String array as the data source, however the data source could be a data table maintained in an Excel file, or relational database. A simple Java class, linked to the test script, provides an interface to retrieve the data "sets" one set at a time. Using this Data Provider class can later be adapted to use more advanced testing management toolsets.

The following code shows a simple class that defines a getData() method that provides an array of String data for each iteration of the test script. The Strings are then converted by a DataRecord (FlightData class in this example) class into the proper object format for each data item.

The example is used in conjunction with a test script for a Flight Reservation application. Each record includes a departure airport, arrival airport, departure date, and return date.

Copy
public class FlightInfo {
 private static String[][] trips = {{"EWR", "LAX", "10.08", "21.08"}, 
     {"ORD", "IAH", "31.08", "05.09"}};
 private int _numTrips = 2;
 private int _index = 0;
 public String[] getData() {
     if (_index >= _numTrips)
         return trips[_numTrips];
     else
         return trips[_index++];
     }
 public int numRows() {
     return _numTrips;
     }
 public FlightInfo() {
     _index = 0;
     }
}

The class includes a method numRows() that returns the number of data-sets available. This is used by the test script to iterate over the number of test runs in the test-script:

Copy
for (int i = 0; i < myTrips.numRows(); i++) {
    // get the data from the dataProvider
    String[] trip = myTrips.getData();
    // create the instance of the dataRecord class with the data record for this 
    FlightData tripInfo = new FlightData(trip);
    //rest of the test script
    ....
    }

See here for a more complete example of a Data Provider class.