How to Read the csv file data one by one and put into variable Using Groovy

余生颓废 提交于 2019-12-13 02:48:42

问题


Here i am facing One problem that. i want to read the csv file data and one by one put it into a variable and that variable i want to assign a next Http Request let say ids.csv file which consisting of values like this

23333
23334
23335
22336
23336

I am using Jsr223 PreProcessor code:

def csvfile = new File('D:/datas/id/ids.csv')
def lines =csvfile.readLines()
lines.each { String line ->
  vars.put('Id_value', line.toString())
}

If it is wrong, how to do this with simple code?


回答1:


You need to add a some form of counter to your JMeter Variables reference names, your current code will create only one Id_value variable with the value of 23336, you need to amend it like:

def csvfile = new File('D:/datas/id/ids.csv')
def lines =csvfile.readLines()
lines.eachWithIndex {line, idx ->
    vars.put('Id_value_' + idx, line)
}

And you will get:

Id_value_0=23333
Id_value_1=23334
Id_value_2=23335
Id_value_3=22336
Id_value_4=23336

More information:

  • Groovy Collection.eachWithIndex()
  • Groovy is the New Black



回答2:


You can emulate JMeter CSV data set which add variables with different suffixes, example in tutorial:

String Filename = vars.get("GETfile");
String fileContents = new File(Filename).getText('UTF-8');
def lines = 0  ;
    fileContents.eachLine { line ->
        lines++;
        vars.put("CSVLine_" + lines, line);
    }
vars.put("GETfileLength",lines.toString()) ; 

and then loop the variables using ForEach Controller:



来源:https://stackoverflow.com/questions/48008527/how-to-read-the-csv-file-data-one-by-one-and-put-into-variable-using-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!