简体   繁体   English

JMeter-Groovy脚本变量的串联

[英]JMeter - Groovy script concatenation of variables

Groovy is the preferred scripting in JMeter Groovy是JMeter中的首选脚本

We advise using Apache Groovy or any language that supports the Compilable interface of JSR223. 我们建议使用Apache Groovy或任何支持JSR223的Compilable接口的语言。

The following code in JSR233 Sampler works in Java but not in Groovy JSR233 Sampler中的以下代码在Java中可用,但在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}...""" 我未能使用使用三个引号的答案"""The row Id is: ${row.id}..."""

Currently I use Java as script language and use JMeter ${variable} although is also not recommended : 目前,尽管不建议使用Java作为脚本语言,并使用JMeter $ {variable}:

In this case, ensure the script does not use any variable using ${varName} as caching would take only first value of ${varName} 在这种情况下,请确保脚本不使用任何使用$ {varName}的变量,因为缓存将仅采用$ {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>"; 字符串文本=“ <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. Groovy使用换行符指示语句的结尾,除非它知道下一行必须扩展当前行。 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. “ +”和“-”运算符具有二进制和一元变量,当前(Groovy版本至少为2.5.x)在下一行的开头不支持这些运算符。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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