Jmeter save response data values to a variables and overwrite it with another values from CSV file

1k Views Asked by At

Is it possible in Jmeter to take the variable (for example ${variable_1} which value I received from the response body of HTTP request with the help of regex , read some .csv file and find the row (imagine all the rows have different values) that starts with exact the same value as ${variable_1}, then read next cell in this row (pretty much .csv file contains only 2 columns) and whatever value is there, overwrite it to ${variable_1}? I was told that this is possible with the help of BeanShell, but I'm not really familiar with scripting in it. Any suggestions are greatly appreciated.

1

There are 1 best solutions below

1
On BEST ANSWER

Here you go:

import org.apache.commons.io.FileUtils;
import java.nio.charset.StandardCharsets;

log.info("Previous value of variable_1 = " + vars.get("variable_1"));

List csvLines = FileUtils.readLines(new File("test.csv"), StandardCharsets.UTF_8);

for (String csvLine : csvLines) {
    if (csvLine.startsWith(vars.get("variable_1"))) {
        vars.put("variable_1", csvLine.split(",")[1]);
        break;
    }
}

log.info("New value of variable_1 = " + vars.get("variable_1"));

Demo:

JMeter Beanshell Demo

See How to Use BeanShell: JMeter's Favorite Built-in Component article for more details on using scripting in JMeter tests.

Also be aware than Beanshell has some serious performance drawbacks and isn't compatible with code written in Java 7+ syntax (generics, labmdas, multiple catches, etc.). If you change the variable using one thread somewhere in setUp Thread Group - this is fine, but if the number of threads is high and/or CSV file is big - it is better to consider JSR223 Sampler and Groovy language instead.