As observed that sometimes we need to save the value of a variable to a text or CSV file from output’s response. Such a scenario is especially required at the time of test data generation when a value exists in the response and you need to save it to an external file i.e. csv file.
JMeter has some postprocessor elements to perform the post-request activities which also include saving a variable value to a file.
Methods to save a variable to a file in JMeter
Using BeanShell PostProcessor
- Add a Regular Expression Extractor to a sampler that has (dynamic) values to save to a file (Example: param1 and param2)
- Add a BeanShell PostProcessor under the same sampler
- Paste the below code in the script section of BeanShell PostProcessor
import org.apache.jmeter.services.FileServer;
String path=FileServer.getFileServer().getBaseDir();
var1= vars.get(“param1”);
var2= vars.get(“param2”);
f = new FileOutputStream(“C://Project/Scenario/Output.csv”,true);
p = new PrintStream(f);
this.interpreter.setOut(p);
p.println(var1+”,” +var2);
f.close();
In the above code, ‘param1’ and ‘param2’ are two variables and their values will be saved in the ‘Output.csv’ file which is located at ‘C://Project/Scenario/’. You can change these values as per your test script.
If you have to save the value of only one variable then use the below code.
import org.apache.jmeter.services.FileServer;
String path=FileServer.getFileServer().getBaseDir();
var1= vars.get(“param1”);
f = new FileOutputStream(“C://Project/Scenario/Output.csv”,true);
p = new PrintStream(f);
this.interpreter.setOut(p);
p.println(var1);
f.close();
Using JSR223 PostProcessor
- Add a Regular Expression Extractor to a sampler that has (dynamic) values to save to a file (Example: param1and param2)
- Add a JSR223 PostProcessor under the same sampler
- Write down the below code in the script section of JSR223 PostProcessor
import org.apache.commons.io.FilenameUtils;
var1 = vars.get(“param1”);
var2 = vars.get(“param2”);
f = new FileOutputStream(“C://Project/Scenario/Output.csv”, true);
p = new PrintStream(f);
p.println(var1+”,”+var2);
p.close();
f.close();
In the above code, ‘param1’ and ‘param2’ are two variables and their values will be saved in the ‘Output.csv’ file which is located at ‘C://Project/Scenario/’. You can change these values as per your test script.
If you have to save the value of only one variable then use the below code.
import org.apache.commons.io.FilenameUtils;
var1 = vars.get(“param1”);
f = new FileOutputStream(“C://Project/Scenario/Output.csv”, true);
p = new PrintStream(f);
p.println(var1);
p.close();
f.close();
So, above are two simple methods in JMeter to save the value of the variables to a file.