这是请求JSON
{
"Transaction": {
"TrType": "Vehicle",
"CustomerType": "${__chooseRandom(Individual,Company,)}",
},
"IndividualClient": {
"firstName": "test first name",
"lastName": "test last name"
}
"CompanyClient": {
"CompanyName": "test company name",
}
}
因此,如果客户类型=个人,则生成其他人生成公司。
我使用了JSR223预处理器。
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
def jsonRequest = null
JsonSlurper jsonSlurper = new JsonSlurper()
jsonRequest = jsonSlurper.parseText(sampler.getArguments().getArgument(0).getValue())
println(JsonOutput.prettyPrint(JsonOutput.toJson(jsonRequest)))
if (jsonRequest.Transaction.CustomerType.equalsIgnoreCase("Individual")) {
jsonBuilder = new JsonBuilder()
jsonBuilder.IndividualClient {
firstName "test first name"
lastName "test last name"
}
vars.put("customertypedetails",jsonBuilder.toPrettyString())
println(vars.get("customertypedetails"))
} else {
jsonBuilder2 = new JsonBuilder()
jsonBuilder2.CompanyClient {
companyName "test company name"
}
vars.put("customertypedetails",jsonBuilder2.toPrettyString())
println(vars.get("customertypedetails"))
}
我用于此目的的参考链接。 https://examples.javacodegeeks.com/jvm-languages/groovy/groovy-json-example/
这个$ {customertypedetails}我在我的JSON中用作;
{
"Transaction": {
"TrType": "Vehicle",
"CustomerType": "${__chooseRandom(Individual,Company,)}",
},
${customertypedetails}
}
但我得到了例外
javax.script.ScriptException:groovy.json.JsonException:expecting'}' 或','但得到当前char'$',其int值为36
当前字符读取为'$',int值为36 '}'或','但得到当前字符'$',int值为36行 数字32索引号907 $ customertypedetails,.. ^ at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:320) 〜[Groovy的全2.4.13.jar:2.4.13]
当我打印时(vars.get(“customertypedetails”)我正在
{
"IndividualClient": {
"firstName": "test first name",
"lastName": "test last name"
}
}
而不是
"IndividualClient":
{
"firstName": "test first name",
"lastName": "test last name"
}
答案 0 :(得分:0)
鉴于您使用JsonBuilder,您将获得有效的JSON,即以{
开头,以}
结尾。
如果由于某种原因这是你不想要的东西,你可以删除起始和尾随花括号,如:
def ctd = vars.get('customertypedetails')
ctd = ctd.substring(ctd.indexOf('{') +1,ctd.lastIndexOf('}'))
vars.put('customertypedetails',ctd)
有关在JMeter测试中使用Groovy脚本的详细信息,请参阅Apache Groovy - Why and How You Should Use It文章。