Search code examples
jmeterbeanshell

JMeter - Generate objects and add to array


So I want to stress test my websocket-communication and the server by sending a high load of messages. The thing is that the messages are formatted in a peculiar way, and I'm struggling with generating the correct data.

So each time I'm sending a message from the client, the emitted message to the server looks kinda like this:

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"}
 ] 
}]

Where each time a new message is created, the message is added to the body. So if I send a new message, the body would look like this:

 "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"}
 ] 

I'm wondering how I could loop this process with JMeter (I guess by using Beanshells Preprocessor somehow). That is, I want so that each thread loop adds to that array body with a new message. I need some array list that keeps the data through each loop, and adds a new message that looks like this:

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

on each thread loop.

I have a CSV-file that contains messages that I'm setting to the variable MESSAGE:

message1,
message2

And guess I need some function like this (Not correct Java syntax, translated to 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);

But I have no experience with Java and Beanshell, and can't figure out how to do this. I would really appreciate any help!


Solution

  • Given you have body JMeter Variable with the value of

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

    You can add another entry with a JSR223 Test Element and the code like:

    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())
    

    Demo:

    JMeter Groovy Add JSON

    More information: