| Cogitek RIATest 3 Documentation | Copyright © Cogitek Inc. |
Sometimes you want certain actions to be performed on your application and for these actions to use external data sources instead of values hard-coded in the script. For example you may have a script that registers users in your system. You have a CSV file with user name, password and other details and want your test to use the data from this CSV file to create users. This is called data-driven testing and making your test actions use variable values instead of hard-coded values is called parametrization.
Let us consider a simple application that can register users if we execute the following actions in our script:
FlexButton("Create User")=>click();
FlexTextArea("Name")=>textInput("John");
FlexTextArea("Password")=>textInput("mypass123");
FlexButton("OK")=>click();
You now want these actions to be repeated for every user and you also want the data from a CSV file to be used, instead of a hard-coded name and password.
The first step is to parametrize the actions, i.e. replace hard-coded values with variables. We will at the same time make these four actions a user-defined function that can be called from anywhere. The function with parametrized actions looks like this:
function createUser(name,password)
{
FlexButton("Create User")=>click();
FlexTextArea("Name")=>textInput(name);
FlexTextArea("Password")=>textInput(password);
FlexButton("OK")=>click();
}
Now we can call this function from anywhere in the script to create a user. For example to create a user "John" with password "mypass123" we can write:
createUser("John","mypass123");
We have now parametered a set of actions and made it a callable function.
Next we see how to read multiple name and password details from a CSV file and call createUser function to create multiple users. We will use the built-in object CSVStream to read the CSV file. Let us assume the file name is users.csv and the first column in the file is the name, the second column is the password. Our data driven test will look like this:
function createUser(name,password)
{
FlexButton("Create User")=>click();
FlexTextArea("Name")=>textInput(name);
FlexTextArea("Password")=>textInput(password);
FlexButton("OK")=>click();
}
// Open CSV file
var fs = new FileStream();
fs.open("users.csv",FileMode.READ);
var csv = new CSVStream(fs);
// Iterate over lines
while (true)
{
try
{
// Read a line from CSV file
var line = csv.readLine();
// If no more lines break iteration
if (line==false)
break;
// The first field is name
var name = line[0];
// The second field is password
var password = line[1];
// Create a user
createUser(name,password);
}
catch (e)
{
// An error occurred, break iteration
break;
}
}
That's it. You can modify this example to suit your own testing. Unlike our simple createUser() function, your actual test may be much more sophisticated and may require more parameters but the concept stays the same.