1

I have extracted a value from JSON response of an API with jmeter let's call it ${newID}. Now I want to paste this newID in all the values of a column ID2 (image attached for reference). Then I need to pass the updated CSV as part of file upload to another API. I have just started using Jmeter, please let me know how I can perform file edit and upload with beanshell script or any other way with Jmeter.

CSV image

CSV image

This is the script I've added in BeanShell post processor but it's not replacing the values:

`import org.apache.commons.io.FileUtils;

File csvFile = new 
File("/my/file/path/dist.csv");
List lines = FileUtils.readLines(csvFile);
String row2 = lines.get(1); 
String[] cells = row2.split(",");
String cell2 = cells[1]; //get the value of old storeID

String fileData = FileUtils.readFileToString(csvFile);
fileData = fileData.replaceAll(cell2, ${StoreID});
FileUtils.writeStringToFile(csvFile, fileData);`
A. A.
  • 11
  • 2

1 Answers1

1

If you need to replace this 424 with the value of ${newID} variable you could do something like:

new File( 'new.csv' ).withWriter { w ->
    new File( 'original.csv' ).eachLine { line ->
        w << line.replace( '424', vars.get('newID') ) + System.getProperty('line.separator')
    }
}

The above code will generate a brand new file new.csv in your current working directory and replace all the occurrences of 424 with the value of ${newID} JMeter Variable.

The code can be placed in any JSR223 Test Element of your choice

Be aware that the approach is suitable for single-threaded execution only, i.e. if you're doing functional testing, for multiple threads (concurrent users) it may lead to data corruption and it's better to use Flexible File Writer (all 3 columns need to be declared as Sample Variables)

Dmitri T
  • 159,985
  • 5
  • 83
  • 133
  • Actually I can't just write '424' because this id will update each time, so need it to be dynamic. I've updated the question with my beanshell code though, but it's not really doing the job could you tell me where I'm wrong? – A. A. Jun 02 '21 at 12:13