JMeter - 生成对象并添加到数组

时间:2018-05-17 12:23:32

标签: jmeter beanshell

所以我想通过发送大量消息来强调测试我的websocket-communication和服务器。问题在于消息的格式是以一种特殊的方式进行的,而且我正在努力生成正确的数据。

因此,每次我从客户端发送消息时,发送到服务器的消息看起来都是这样的:

42["tickets","ticket_message",
{"ticket":{
 "body":[
  {"received":"2018-05-17T11:28:51.000Z","fromName":"Jesper Pedersen","body":"test\n"},
  {"received":"2018-05-17T13:30:53+02:00","body":"Yo","fromName":"Futurum Digital"}
 ] 
}]

每次创建新邮件时,邮件都会添加到正文中。因此,如果我发送新消息,正文将如下所示:

 "body":[
  {"received":"2018-05-17T11:28:51.000Z","fromName":"Jesper Pedersen","body":"test\n"},
  {"received":"2018-05-17T13:30:53+02:00","body":"Yo","fromName":"Futurum Digital"},
  {"received":"2018-05-17T13:38:43+02:00","body":"Yo again","fromName":"Futurum Digital"}
 ] 

我想知道如何用JMeter循环这个过程(我想通过某种方式使用Beanshells Preprocessor)。也就是说,我希望每个线程循环都使用新消息添加到该数组主体。我需要一些数据列表来保存每个循环中的数据,并添加一条如下所示的新消息:

{"received":"new date","body":"new message again","fromName":"Futurum Digital"}

在每个线程循环上。

我有一个CSV文件,其中包含我设置为变量MESSAGE的消息:

message1,
message2

我想我需要一些像这样的函数(不正确的Java语法,翻译成javascript-ish):

var messages = ${SOME_GLOBAL_MESSAGES_ARRAY}
var message = {"received": new Date().toString(),"body":"${MESSAGE}", "fromName":"Futurum Digital"}

messages.push(message)
vars.put('messageList', messages);

但我没有Java和Beanshell的经验,也无法弄清楚如何做到这一点。我真的很感激任何帮助!

1 个答案:

答案 0 :(得分:1)

假设body JMeter Variable的值为

{
  "body": [
    {
      "received": "2018-05-17T11:28:51.000Z",
      "fromName": "Jesper Pedersen",
      "body": "test\n"
    }
  ]
}

您可以使用JSR223 Test Element添加另一个条目,例如:

def json = new  groovy.json.JsonSlurper().parseText(vars.get('body'))
def body = json.body
def newEntry = new groovy.json.internal.LazyMap()
newEntry.put('received', '2018-05-17T13:30:53+02:00')
newEntry.put('fromName', 'foo')
newEntry.put('body', 'bar')
body.add(newEntry)
vars.put('body', new groovy.json.JsonBuilder(json).toPrettyString())

演示:

JMeter Groovy Add JSON

更多信息: