简体   繁体   中英

JMeter - Groovy script concatenation of variables

Groovy is the preferred scripting in JMeter

We advise using Apache Groovy or any language that supports the Compilable interface of JSR223.

The following code in JSR233 Sampler works in Java but not in Groovy

String a= "0"+"1" +
"2" 
+"3";
log.info(a);

I found the reasons for + operator not to work as expected,

but what is the solution is I want to concatenate several variables to a script?

I failed to use answer of using three quotes """The row Id is: ${row.id}..."""

Currently I use Java as script language and use JMeter ${variable} although is also not recommended :

In this case, ensure the script does not use any variable using ${varName} as caching would take only first value of ${varName}

String text ="...<id>${id}</id><id2>${id2}</id2>...";

What's a better approach in groovy in such case?

EDIT :

Try using << but different error where it split to new line

String text ="<id>" <<vars["id1"] << "<id><id2>" 
<< vars["id2"] << "<id2>";

Receives an error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script12.groovy: 2: unexpected token: << @ line 2, column 1.
   << vars["id2"] << "<id2>";

Why don't you use :

String text ="<id>" <<vars["id1"] << "<id><id2>" << vars["id2"] << "<id2>";

It works for me

If I had a hashmap to concat like yours, I would try:

def vars = ["id": "value", "id2": "value2", "id3": "value3"]

String text = ""
vars.each { k, v ->
    text += "<${k}>${v}</${k}>"
}

println text

Groovy uses the new line character to indicate end of statement except in cases where it knows the next line must extend the current one. Numerous binary operators on the start of the next line are supported. The '+' and '-' operators have binary and unary variants and currently (Groovy versions at least up to 2.5.x) don't support those operators at the start of the next line. You can place the operator on the end of the previous line (as in your first line) or use the line continuation character at the end of the previous line:

String a = "0" + "1" +
"2" \
+ "3"
log.info(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM