JMETER | How To Write Data From Response To A CSV File

Problem Statement:

As an Automation Tester,
I want to Save Response Data to file
And I want to extract some portion of response
So that I can generate .csv file which can be utilized further

Why we need Response to store?

Solution:

API under Jmeter Test
API Details:
-----------------
End-point:

URL
Input Param:
name = Ahmed
Jmeter Structure
* Test plan -> Add -> Thread (Users) -> Thread Group
* Thread Group -> Add ->
- Config Element -> User Defined Variables
- Sampler -> HTTP Request
- Listener -> Save Responses to a file
- Listener -> View Results Tree
User Defined Variables
HTTP Request (GetByName)
Response in View Tree

Where we have reached so far?

A) Need to extract details from response andB) Only extracted details should be saved to .csv file for further use.
* Thread Group -> Add -> Sampler -> Debug Sampler
* HTTP Request -> Add -> Post Processors -> XPath2 Extractor
XPath2 Extractor
Where-* XPath query : //name
* Match No. should be -1 ( extract all results, they will be named as <variable name>_N (where N goes from 1 to Number of results))
Debug Sampler Response in View Tree
* HTTP Request -> Add -> Post Processors -> JSR223 PostProcessor
import org.apache.commons.io.FileUtils
import java.text.SimpleDateFormat;
// Get total number of matches. (Returns string)
def resultCount = vars.get("ExtractedName_matchNr")
log.warn 'Output to jmeter console' + resultCount
// Generate timestamp to create uniue file name.
String fileSuffix = new SimpleDateFormat("ddMMyyyyHHmm").format(new Date())
// Create file Object
f = new File("results_"+fileSuffix+".csv")
for (int i=1; i<=resultCount.toInteger(); i++)
{
// Get each matching result one by one.
records = vars.get("ExtractedName_"+i)
// Write result to csv file.
FileUtils.writeStringToFile(f,records + System.getProperty("line.separator"),true)
}
JSR223 PostProcessor-To extracted result to csv file

Conclusion:

If you enjoyed the article, do me a favor and smack the 👏👏 👏 multiple times — your support means the world to me!

Agile Product Delivery Manager | Scrum Master (PRINCE2, CSPO™, CSM™, SFC™, ISTQB)