Using Templates for API Load Testing
Table of Contents
Intermediate - This article is part of a series.
In this entry, we discuss the topic of using templates (templates) in the load testing process for APIs. This blog is, to some extent, a continuation of our blog from our previous post where we proposed the advantages of altering JMeter scripts externally and dynamically. While it is true that this technique can be complex, it is important to know about it and incorporate it into your toolset.
Example #
As we know, typically API load tests require sending a block of data in the JSON format. (Note: this block of data is known as payload in English.) This block consists of pairs of names/values like this:
{
"Paciente":{
"Identificación": "123456789",
"Médico": "Dr. MataSanos",
"Hospital": "LaBuenaMuerte"
}
}
In our example, the purpose of the test is to create patients in a certain application. To do this, we include an element HTTP Request where we add the payload in the Body Data of the order:
The graph shows how the variable Identification is assigned a random number using part of the variable __UUID. We also define variables Doctor and Hospital, whose values will be read using the element [CSV Data Set Config]. This is the standard process.
The Problem #
The problem arises when the components of the API change, causing us to have to edit the script (using the GUI) to alter the JSON structure. This problem is compounded when this structure is used by multiple scripts.
{
"Paciente":{
"Identificación": "LT${__substring(${__UUID()}, 0, 8)}",
"Médico": "${__eval(${MD_NAME})}",
"Hospital": "${__eval(${HOSPITAL_NAME})}"
}
}
It is important to note that this template contains only the references to the values of the variables. The data (medical and hospital) currently exist in the CSV file (as we mentioned earlier). Note that we use the JMeter function __eval to force the evaluation of the variables at execution time.
We implemented this technique in three steps:
Step 1: #
Using the Configuration element User Defined Variables, we create/assign a variable that contains the location where the template file resides.
Step 2: #
Using the Pre-Processor User Parameters element, we create/assign a parameter (PATIENT_JSON) that during execution takes on the value of the template, in this way:
CASE_JSON={
"Paciente":{
"Identificación": "LT${__substring(${__UUID()}, 0, 8)}",
"Médico": "${__eval(${MD_NAME})}",
"Hospital": "${__eval(${HOSPITAL_NAME})}"
}
}
Step 3: #
Finally, in this step, we add an expression to the Body Data of the HTTP Request, which will assign dynamic values to the variables MD_NAME and HOSPITAL_NAME at execution time. These values are extracted from the respective CSV file.
Conclusion #
Using templates in a script provides flexibility and productivity that result in a significant increase in the efficiency of testing scripts.