JMeter – How to save a variable to a file?

Sometimes you need to save the value of a variable to a text or CSV file. Such a scenario 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.

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

  1. Add a Regular Expression Extractor to a sampler which has (dynamic) values to save to a file (Example: favicon and src)
  2. Add a BeanShell PostProcessor under the same sampler
  3. 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("favicon");      
var2= vars.get("src");

f = new FileOutputStream("C://Project/Scenario/testdata.csv",true);
p = new PrintStream(f); 

this.interpreter.setOut(p); 
p.println(var1+"," +var2);

f.close();

In the above code, ‘favicon’ and ‘src’ are two variables and their values will be saved in ‘testdata.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 below code.

import org.apache.jmeter.services.FileServer;

String path=FileServer.getFileServer().getBaseDir();

var1= vars.get("favicon");  
    
f = new FileOutputStream("C://Project/Scenario/testdata.csv",true);
p = new PrintStream(f);
 
this.interpreter.setOut(p); 
p.println(var1);

f.close();

Using JSR223 PostProcessor

  1. Add a Regular Expression Extractor to a sampler which has (dynamic) values to save to a file (Example: favicon and src)
  2. Add a JSR223 PostProcessor under the same sampler
  3. Write-down the below code in the script section of JSR223 PostProcessor
import org.apache.commons.io.FilenameUtils;

var1 = vars.get("favicon");
var2 = vars.get("src"); 

f = new FileOutputStream("C://Project/Scenario/testdata1.csv", true);
p = new PrintStream(f);

p.println(var1+","+var2);

p.close();
f.close();

In the above code, ‘favicon’ and ‘src’ are two variables and their values will be saved in ‘testdata1.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 below code.

import org.apache.commons.io.FilenameUtils;

var1 = vars.get("favicon");

f = new FileOutputStream("C://Project/Scenario/testdata1.csv", true);
p = new PrintStream(f);

p.println(var1);

p.close();
f.close();

So, these are two simple methods in JMeter to save the value of the variables to a file.


Leave a Reply

Your email address will not be published. Required fields are marked *