When doing API testing, you may find that your test data can become unmanageable. For example, if your test uses a collection of XML files or JSON files, your data files can become accumulate and become cluttered. To reduce this technical debt, consider creating your test data dynamically using a single data file.
In the first tutorial in this series, I ran a GET request against a public API.
In the second tutorial, I showed how to easily build JSON data using a string.
In this installment we will generate JSON data using a CSV data file.
First add two more variables to your UDV:
${jsonBodyData} = This will be used to store the new JSON body data
${ScriptPath} = This is the local path where the CSV is saved
Next create a CSV file to hold your test data:
(Text format)
(Spreadsheet format)
In order to pull test data from the CSV file, you must add a config element to the script called CSV Data Config. Assign the ${ScriptPath} variable inside this element:
Now add an HTTP Request to your script and a JSR223 PreProcessor underneath.
Select groovy in the language dropdown and paste the following code:
import groovy.json.*
import groovy.json.JsonBuilder
def jsonBuilder = new groovy.json.JsonBuilder()
jsonBuilder
{
custid Integer.parseInt(vars.get("customerId"))
custname vars.get("customerName")
ordcolor vars.get("orderColor")
ordnumber Integer.parseInt(vars.get("orderNumber"))
}
vars.put("jsonBodyData", jsonBuilder.toPrettyString())
log.info("JSON body data = " + "\n" + vars.get("jsonBodyData"))
In this example we used a groovy jar called JsonBuilder to build the request data. Please note that the customerId and orderNumber were both formatted as an Integer.
The JSON data has been formatted and saved inside the ${jsonBodyData} variable.
Apply this variable to the HTTP Request. Also, make sure that the POST method has been selected inside the HTTP Request:
Run the request. If everything has been setup correctly, you should see the formatted JSON data inside the listener and the log viewer.