在 jmeter 中使用 Beanshell 验证 JSON 响应

Validating JSON Response using Beanshell in jmeter

我正在尝试使用 Beanshell 断言在我的 jmeter 中断言 Json 响应。下面是我的代码。

import org.json.JSONObject;
import org.json.JSONArray;
import java.lang.String;
import org.apache.log.Logger;

try{
  String jsonString = prev.getResponseDataAsString();
  JsonObject jsonobj = JsonObject.readFrom(jsonString);
  JsonArray jsonarr = jsonobj.get("items").asArray();
  String pickup = jsonarr.get(2).asObject().get("CM_NAME").asString();
  log.info(pickup); 
 }
catch(Exception e)
{
 log.info("beanshell Exception "+e.getMessage());
}

这是我必须验证的 Json 路径

$.items[2].CM_NAME

在我 运行 脚本之后,我得到以下脚本。

Assertion failure message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import org.json.JSONObject; import org.json.JSONArray; import java.lang.String; . . . '' : Typed variable declaration : Class: JsonObject not found in namespace

我使用的是 jmeter 版本 2.11。谁能帮我让我的脚本正常工作,我的代码是否正确?

我建议你改用 JsonPath,这正是你想做的。

此外,升级到 JMeter 3.1,它已经在其类路径中嵌入了这个库,或者下载 JAR 文件并将其放入 /lib/ext。

完整代码示例:

import com.jayway.jsonpath.JsonPath;

String author0 = JsonPath.read(document, "$.store.book[0].author");
Failure = !"John Smith".equals(author0);
if (Failure) {
  FailureMessage = "Expected John Smith as author";
}

如果你真的想走这条路,你需要确保你有 relevant JSON library somewhere in JMeter Classpath(通常将 jar 放到 JMeter 的 "lib" 文件夹中并重新启动 JMeter 以拾取它就足够了)


展望未来,我建议使用不同的方法,例如:

  1. JSON Path Assertion available via JMeter Plugins, you can use your JSON Path query directly there. You can install JSON Path Assertion via JMeter Plugins Manager

  2. 切换到 JSR223 Assertion and Groovy language. Groovy has built-in JSON support 这样您就不需要任何额外的库了。例如,如果您有以下 JSON 响应:

    {
      "items": [
        {
          "CM_NAME": "foo"
        },
        {
          "CM_NAME": "bar"
        },
        {
          "CM_NAME": "baz"
        }
      ]
    }
    

    并且您需要提取 baz 值,您可以使用以下 Groovy 代码来完成:

    def response = SampleResult.getResponseDataAsString()
    def json = new groovy.json.JsonSlurper().parseText(response)
    
    log.info(json.items[2].CM_NAME)