问题
I need to set and get variables in Jmeter for API automation.
I am using the groovy script for same.
I have achieved same using code as below:
import org.apache.jmeter.util.JMeterUtils;
JMeterUtils.setProperty("PC_CREATED_PROMO_CODE", "shubhamvalue");
log.info("will it work? ="+JMeterUtils.getProperty("PC_CREATED_PROMO_CODE"))
Now the problem is I am not able to see the value in any contanier where I can set my hardcode values like token, baseURL, Headers. it should be similar we do in SOAP-UI or postman tests.
Please let me know if I can see these setProperty values in file/section/container in Jmeter.
Or suggest me any other workaround which is more feasible for same.
Any workaround will be helpful and appreciated in advance.
回答1:
If you need to get and set variables I would recommend using vars
shorthand
As per documentation
Properties are not the same as variables. Variables are local to a thread; properties are common to all threads, and need to be referenced using the __P or __property function.
So I would suggest setting variables as: vars.put('foo', 'bar')
and accessing them as ${foo}
where required as my expectation is that you will be getting different PC_CREATED_PROMO_CODE
for each thread (virtual user)
Also be aware that it is also recommended to avoid scripting where possible so consider going for JSON Extractor instead.
回答2:
To view properties in file/section you can use 2 functions __property or__P while the second will return 1 as default. in your case
${__property(PC_CREATED_PROMO_CODE)}
${__P(PC_CREATED_PROMO_CODE)}
For example you can change next sampler name to Post2 ${__property(PC_CREATED_PROMO_CODE)}
BTW you can set property use props
instead
props.setProperty("PC_CREATED_PROMO_CODE", "shubhamvalue" )
Example of use in HTTP Header Manager, adding cotentType from property:

回答3:
1) In JMeter GUI mode, under WorkBench, create Property Display by WorkBench > Add > Non-Test Elements > Property Display. Then select JMeter Properties checkbox to view all the exist properties
props.put("shubhamKey", "shubhamValue")
When you execute this code the property will set in a property file and you can see it in below location:
WorkBench > Add > Non-Test Elements > Property Display.
2) Now if you are want to use User Defined Variables in your scripts you can call value like below:
vars.get("shubhamUserKey")
Still looking to set the value from code in User Defined Variables
来源:https://stackoverflow.com/questions/48441512/how-to-set-and-get-environment-variables-in-jmeter-to-test-apis