如何在jmeter中使用beanshell预处理器删除空参数


问题内容

我正在尝试读取包含500多个行的csv文件,并且每行将作为对API的请求。现在我的问题是某些参数具有空字符串,我想设置一个条件,以防万一如果参数返回空字符串,则在点击API之前先从请求主体中删除该参数

以下是我的json

{
  "body": {
    "Id1": "${Id1}",
    "addressId": "${addressId}",
    "languageCode": "${languageCode}",
    "tempId": "${tempId}"
}

现在阅读csv后,我在请求正文中得到以下值

{
  "body": {
    "Id1": "1",
    "addressId": "1233",
    "languageCode": "E",
    "tempId": ""
}

如您所见,tempId具有空字符串。现在,我正在使用bean-shell预处理程序来删除它,但是没有运气

Object requestBody = sampler.getArguments().getArgument(0).getValue();

if (requestBody.get("tempId").equals("")){
    sampler.getArguments.removeArgument("tempId");
}

当我查看结果树时,我看不到tempId从请求中删除。我将不胜感激任何帮助


问题答案:

避免使用Beanshell弃用和降低性能。

使用groovy代替此代码:

import org.apache.jmeter.config.Arguments;
def request = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
def newRequest = evaluate(request.inspect())
request.body.each { entry ->
    if (entry.getValue().equals('')) {
        newRequest.body.remove(entry.getKey())
    }
}
def arguments = new Arguments();
sampler.setArguments(arguments);
sampler.addNonEncodedArgument('', new groovy.json.JsonBuilder(newRequest), '')
sampler.setPostBodyRaw(true)

看到:

如果您想正确学习jmeter,这本书将为您提供帮助。