如何在 JMeter 的 HTTP POST 请求正文中包含 groovy 脚本的结果?

How to include the result of a groovy script in the body of a HTTP POST request in JMeter?

使用在 BeanShell 预处理器中编写的脚本 groovy,我生成了一个带有一些参数的随机 JSON 对象。我无法在 JMeter 的 HTTP POST 请求正文中包含这个创建的对象(我在脚本中使用了 JsonBuilder)。 这是我创建 JSON 对象的脚本片段:

...
def json = new JsonBuilder();
def root = json parameter1: value1, parameter2: value2, parameter3: value3, parameter4: value4;

bsh.shared.root.process();
vars.put("BODY", root.toString());

我想在 JMeter 中的 HTTP POST 请求的 BODY DATA 部分传递这个对象:

${BODY}

这是生成的响应数据:

The request content was malformed:
Unexpected character '$' at input index 0 (line 1, position 1), expected JSON Value:
${BODY}
^

你不能使用 Groovy in the Beanshell Pre-Processor as Groovy and Beanshell 是不同的野兽。

例如,您尝试使用 exists in Groovy but doesn't exist in Beanshell and if you open jmeter.log 文件的 def 关键字,您将看到以下内容:

BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``def json = new JsonBuilder();'' : Typed variable declaration : Class: def not found in namespace

由于您的脚本在第一行失败,因此您的 ${BODY} 变量未定义并且由 HTTP 请求采样器按原样发送,因此您收到此错误。

切换到 JSR223 预处理器,确保从 "Language" 下拉列表中选择 groovy 并仔细检查 jmeter.log[=34 中没有错误=] 文件。

更多信息: