Jmeter:使用Beanshell断言来测试空JSON值

时间:2013-12-20 22:59:27

标签: json jmeter beanshell

SI尝试测试可能为null的JSON值。

首先我尝试使用jp @ gc - JSON Path Assertion。但是,如果它遇到空值,那么它似乎不会返回任何内容或定义变量。

所以我试图让它像这样工作:

  • 使用jp @ gc - JSON Path Extractor尝试将值提取到变量。
  • 使用Beanshell Assertion测试变量是否存在或具有空值
  • 如果变量不存在,或者存在并且具有空值,我知道JSON值为null。

我之前没有用Jmeter写过任何脚本,所以我可能会做一些明显错误的事情,但这是我在Beanshell Assertion中尝试的内容:

try {
  String myValue = vars.get("myValue");
  log.info("myValue =" + myValue);
}
catch (e) {
  log.info( "caught exception: "+e );
  String myValue = null;
}


if (myValue.length() > 0  && myValue != 0 ){
 Failure = true;
 FailureMessage = "myValue was " + myValue + ".";
}
else{
  Failure = false;
}

对于此测试,空值实际上通过了测试。

我遇到的问题是try / catch块不起作用。相反,我在日志中看到以下消息:

jmeter.assertions.BeanShellAssertion: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval    Sourced file: inline evaluation of: ``import org.apache.jmeter.util.JMeterUtils; try {   //myValue = JMeterUtils.get . . . '' : Attempt to resolve method: length() on undefined variable or class name: myValue

有谁能告诉我我做错了什么和/或如何让这个空JSON值测试工作?

3 个答案:

答案 0 :(得分:2)

此代码中有许多错误的内容;

  1. 错误消息表明它无法识别myValue。那是因为它是在try-catch块中定义的。要修复,您必须在try-catch块之前声明String myValue。但是...
  2. 事实证明,毕竟你不需要try-catch块,因为vars不会抛出任何异常而是will return null when the given key does not exist
  3. 要检查myValue是否为空,请使用myValue != null
  4. 这是更新后的代码:

    String myValue = vars.get("myValue");
    if(myValue != null){
      log.info("myValue =" + myValue);
      Failure = true;
      FailureMessage = "myValue was " + myValue + ".";
    }else{
      //log something here?
      Failure = false;
    }
    

答案 1 :(得分:2)

您需要修改代码。

  1. Beanshell is not very Java,除非您明确指定,否则将处理所有子句。
  2. 您的myValue字符串未定义,您需要将其设置为“全局”
  3. 正确的代码看起来很简单:

        String myvalue = vars.get("json");
    
        if (myvalue == null) {
            Failure = false;
        } else if (myvalue.length() > 0) {
            Failure = true;
            FailureMessage = "Expected \"myvalue\" to be null, Actual: " + myvalue;
        }
    

答案 2 :(得分:0)

http://jmeter-plugins.org/wiki/JSONPathAssertion/

自jp @ gc v.1.2.1 - JSON Path Assertion以来,可以针对null值进行验证。但是,在撰写此评论时,它并不是稳定的版本。 可以从这里下载:http://jmeter-plugins.org/downloads/all/#Developer-Snapshots

相关问题