Jmeter:使用Beanshell断言测试空JSON值 [英] Jmeter: using a Beanshell Assertion to test a null JSON value
问题描述
SI正在尝试测试可能为null的JSON值.
SI'm trying to test a JSON value that may be = null.
首先,我尝试使用jp @ gc-JSON路径声明.但这似乎不会返回任何内容,也不会在遇到空值时定义变量.
First I tried using jp@gc - JSON Path Assertion. but that doesn't appear to return anything or define the variable if it encounters a null value.
所以我试图让它像这样工作:
So I was trying to get it to work like this:
- 使用jp @ gc-JSON路径提取器尝试将值提取到变量中.
- 使用Beanshell断言测试该变量是否存在或具有空值
- 如果该变量不存在,或者存在并且具有空值,那么我知道JSON值为空.
我以前没有用Jmeter编写任何脚本,所以我可能做错了明显的事情,但这是我在Beanshell断言中尝试过的事情:
I haven't written any scripts with Jmeter before, so I may be doing something obviously wrong, but here is what I've tried in the 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;
}
对于此测试,null值实际上通过了测试.
For this test, a null value actually passes the test.
我遇到的问题是try/catch块不起作用.相反,我在日志中看到以下消息:
The problem I'm running into is that the try/catch block doesn't work. Instead, I see the following message in the log:
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值起作用?
Can anyone tell me what I'm doing wrong and/or how to get this test of a null JSON value to work?
推荐答案
此代码中有很多错误的地方;
There are many wrong things in this code;
- 该错误消息表明它无法识别
myValue
.那是因为它是在try-catch块中定义的.要解决此问题,必须在try-catch块之前声明String myValue
.但是... - 结果是,您根本不需要try-catch块,因为
vars
不会抛出任何异常,但是
- The error message says that it does not recognize
myValue
. That's because it is defined within the try-catch block. To fix, you have to declareString myValue
before the try-catch block. But... - Turns out, you don't need the try-catch block after all, since
vars
won't throw any Exception but will return null when the given key does not exist. - To check if
myValue
is not null, usemyValue != null
.
这是更新的代码:
String myValue = vars.get("myValue");
if(myValue != null){
log.info("myValue =" + myValue);
Failure = true;
FailureMessage = "myValue was " + myValue + ".";
}else{
//log something here?
Failure = false;
}
这篇关于Jmeter:使用Beanshell断言测试空JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!