Test Data for Selenium

We receive quite a few questions through our Support channel involving how to data drive Selenium tests through Flood. There are many ways to achieve this - one of the simplest and most common ways of doing this is by using a simple CSV file structured with columns and rows of data that you would like to use within your test.​​

As you can see in the above example - we've got four different types of data needing to be used within a test - Username, Password, Name (Company), and Short Name (Company).

The first row always contains the Column Name - this is just to aid readability for this test.

To be able to use the CSV file we'll need a nice, easy to use specialised library that makes it very easy for us to use rows of data in sorted columns - I've chosen OpenCSV. OpenCSV is a great library that can be simply added into your existing Selenium script and start using straight away.

Simply add the OpenCSV declaration to the top of your script within the declared Java libraries section:

//Include OpenCSV library and Java File Reader
import java.io.FileReader;
import au.com.bytecode.opencsv.CSVReader;

We now have to declare some string variables for the library. We have the nextLine string array and a FILE_PATH string variable that contains the path used by Flood for the CSV file.

//Declare file paths and associated variables used
String [] nextLine;
String FILE_PATH = "/data/flood/files/MyData_AU.csv";

We now have to create an instance of the OpenCSV reader object so we can use it in each iteration.

//Init the CSV Reader (OpenCSV)
CSVReader reader = new CSVReader(new FileReader(FILE_PATH));
nextLine = reader.readNext();

We can now retrieve data from the CSV file row by row. We'll need to add a few things within the main iterative loop as follows:

while (iterations < 10 || reader.readNext() != null) {
try {
nextLine = reader.readNext();
System.out.println("Username : [" + nextLine[0] + "]");
...

So here we are only doing 10 iterations - and the while loop states that while the number of iterations is less than 10 and the CSV contains rows, execute another iteration of the test.

Each column gets assigned an integer - where 0 is the first column (which is Username), 1 for the second column (Password) and so on.

You can then refer to the data within that column by using: nextLine[x] - where x is the integer of the column needing to be used.

That's It!

When you're happy with your script - you can then try running it on Flood. You will need to upload three components:

  1. Your Selenium script file

  2. The OpenCSV jar file library

  3. Your CSV file(s)

The full script for this example is available for your reference here: https://gist.github.com/jrizio/efc5c06cc594c82ac0e3b8d072084303/archive/59a9f0bd1d51c5a0af23b0f72bfd3083b143f411.zip

Also, the OpenCSV 2.3 library used in this example is available here. (Credit to http://www.java2s.com) ​