Search code examples
javalistjmeterbeanshell

Can't merge a list using addAll method in Jmeter's BeanShell


Trying to merge a list using addAll method in Jmeter's BeanShell, but the BeanShellInterpreter said the method not found.

I tried to merge 2 lists using the tutorial from here.

The list that I want to merge, looks like this:

  1. carID_1=[307,308,304]
  2. carID_2=[305]
  3. carID_3=[306]

And here's the code I wrote:

import java.util.ArrayList;
import java.util.List;

List<Integer> allCarID = new ArrayList<Integer>();
numOfCarID = vars.get("carID_matchNr"); //contains the number of list used for looping
int numOfCarID = Integer.parseInt(numOfCarID);

for (int i = 1; i <= numOfCarID; i++){
    x = vars.get("carID_"+i);
    allCarID.addAll(x);
}

log.info("All Car: " + allCarID);

When I try to run the code, it gives me an error said that Encountered "=" at line 4, column 25.. After some research, I try to change the code to List allCarID = new ArrayList(); and code successfully reached the addAll method.

It show an error like this: Error in method invocation: Method addAll( java.lang.String ) not found in class'java.util.ArrayList'.

Try to change addAllto 'add', the code executed successfully and didn't show an error, but the result I wanted was different.

What I want is a list [307,308,304,305,306], but I got a [[307,308,304], [305], [306]] instead.

Any kind of help is very helpful, thank you in advance.


Solution

    1. You're trying to pass a String to the ArrayList.addAll() function, it won't work as the function expects a Collection.

    2. Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting so consider migrating

    3. The code you wrote doesn't compile so I fail to see how did you get this output

    If you have these carID_1=[307,308,304] stored as Strings you could do something like:

    vars.put('carID_1', '[307,308,304]')
    vars.put('carID_2', '[305]')
    vars.put('carID_3', '[306]')
    vars.put("carID_matchNr", "3")
    
    List<Integer> allCarID = new ArrayList<Integer>();
    
    1.upto((vars.get('carID_matchNr') as int), {
        def carIDs = new groovy.json.JsonSlurper().parseText(vars.get('carID_' + it))
        allCarID.addAll(carIDs)
    })
    
    log.info('All Car: ' + allCarID)
    

    enter image description here

    More information on Groovy scripting in JMeter: Apache Groovy: What Is Groovy Used For?