问题描述
今天调试JMeter脚本的时候,发现了一个让我很困惑的问题.
Today when I was debugging my JMeter script, I found a problem that confused me a lot.
- CSV 数据配置元素:在 CSV 中,我将变量
userId
设置为1001200
- 然后运行下面的脚本,在使用
${userId}
和vars.get("userId")
时得到不同的userId"值.我认为它们应该是相同的值,但似乎不是.运行后vars.put("userId", "-111")
,${userId}
和vars.get("userId")
获得不同的值:
- Then run script below, and get different value of "userId" when using
${userId}
andvars.get("userId")
. I think they should be same value, but it seems not. After runvars.put("userId", "-111")
,${userId}
andvars.get("userId")
get different values:
所以看起来 ${}
和 vars.get()
有一些不同,即使它们的变量是相同的,有人知道原因吗?
so it seems ${}
and vars.get()
have some difference even though their variable is same, does anyone know the reason?
提前致谢.
推荐答案
@user7294900 提供的答案是指选中缓存编译脚本选项的情况.但即使没有检查,您的脚本也会解析定义为 ${varName}
before 执行的变量,而 vars.get("varName")
在执行过程中解决.
Answer provided by @user7294900 refers to the case when Cache compiled script option is checked. But even if it's not checked, your script will resolve variables defined as ${varName}
before execution, while vars.get("varName")
is resolved during execution.
在 JMeter 即将运行任何元素(采样器、预处理器或后处理器)之前,它将获取(每个)文本字段并解析任何变量、函数或内联代码,由 ${...}
到评估时可用的值.因此语法 ${...}
将变量转换为常量字符串,您的代码(对于 Groovy 或任何其他执行引擎)将如下所示:
Before JMeter is about to run any element (sampler, pre- or post-processor), it will take (every) text field and will resolve any variables, functions or inline code, identified by ${...}
to their values available at the time of the evaluation. Thus syntax ${...}
converts variable into a constant string and your code (for Groovy or any other execution engine) will look like this:
log.info("***" + "1001200" + "***");
log.info("***" + vars.get("userId") + "***");
vars.put("userId", "-111");
log.info("***" + "1001200" + "***");
log.info("***" + vars.get("userId") + "***");
因此无论您在执行过程中如何更改变量,它都不会更改,因为它不再是变量.但另一方面,vars.get("userId")
是一个函数调用,每次都会检查变量值.
Thus no matter how you change variable during execution, it won't change since it's no longer a variable. But vars.get("userId")
on the other hand, is a function call and will check variable value every single time.
这篇关于JMeter-使用 ${} 或 vars.get() 获取变量值有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!