Data sources in ReadyAPI are a powerful tool you can use to create data-driven tests. By default, data sources only provide the data they take from the source to any test step that needs it. They cannot modify the data in any way, or control it. For this, you use Groovy scripts. This topic provides examples of some ways you can modify your data-driven tests.
Where to use
There are the following ways to run this script:
- As a Groovy Script test step.
- As a setup or teardown script on the test case level in functional tests.
Examples
Combining Multiple Data Source Values
The following script gets the values from a project and a data source, combines them to a single string and writes them to the test case custom property.
Groovy
// Get values from a data source.
def countryCode = context.expand( '${DataSource#CountryCode}' )
def countryName = context.expand( '${DataSource#CountryName}' )
// Get the project's XmlFragment property.
def frag = context.expand( '${#Project#XmlFragment}' )
// Combine the text of all properties.
def newPropertyValue = frag + countryCode + countryName
// Write the resulting text to the test case property.
testRunner.testCase.setPropertyValue( 'ResultingText', newPropertyValue )
Randomizing Data Source Rows
Most data sources in ReadyAPI return values in sequence. You can use groovy scripts to randomize the order of the returned values each time you run a test. Here is how you organize your test to do this:
-
The original Data Source test step with the data you want to randomize.
-
The Groovy Script test step that creates a list with the data from the data source. Use the following script:
Groovy
// Create a list if necessary.
// If your data source returns multiple properties, create a list for each property you need.
if( context["allRows"] == null ) context["allRows"] = []
// Append the current data source row value to the list.
context["allRows"] << context.expand( '${DataSource#outputProperty}' ) -
The Data Source Loop test step that iterates through the original data source so that you can get all the data it returns.
-
The Groovy Data Source test step that provides random data to your test. Use the following script:
Groovy
// Shuffle the list before returning values.
// Use a separate Groovy Script test step if you do not want to shuffle the list at each iteration.
Collections.shuffle( context["allRows"] )
// Get the value of the current row.
def row = testRunner.testCase.testSteps["DataSource 2"].currentRow
// Return the value as long as it is within the list.
if ( row + 1 <= context["allRows"].size() )
{
result["randomRow"] = context["allRows"][row]
} -
Your test steps that use the data and optionally a data source loop to iterate through it.
Here is what your test case can look like: