Search code examples
scalaperformancefor-loopgatlingscala-gatling

How to get the return value from For loop and pass it to .body(StringBody(session => in Gatling using Scala


How to get the return value from For loop and pass it to .body(StringBody(session => in Gatling using Scala

I have created a method with for loop to generate String Array in gatling with scala

def main(args: Array[String]): Unit = {
    var AddTest: Array[String] = Array[String]()
    for (i <- 0 to 3) {
      val TestBulk: String =
        s"""{ "name": "Perftest ${Random.alphanumeric.take(6).mkString}",
            "testID": "00000000-0000-0000-0000-000000006017",
            "typeId": "00000000-0000-0000-0000-000000011001",
            "statusId": "00000000-0000-0000-0000-000000005058"};"""
      AddTest = TestBulk.split(",")
      //  val TestBulk2: Nothing = AddTest.mkString(",").replace(';', ',')
      // println(TestBulk)
    }
  }

now I want to pass the return value to .body(StringBody(session =>

    .exec(http("PerfTest Bulk Json")
      .post("/PerfTest/bulk")
      .body(StringBody(session =>
        s"""[(Value from the for loop).mkString(",").replace(';', ',')
]""".stripMargin)).asJson

Please help me with the possibilities Please let me know if


Solution

  • You don't need for loop (or var or split) for this. You also do not have ; anywhere, so last replace is pointless.

        val ids = """
           "testId": "foo", 
           "typeId": "bar", 
           "statusId": "baz"
        """
    
        val data = (1 to 3)
         .map { _ => Random.alphanumeric.take(6).mkString }
         .map { r => s""""name": "Perftest $r"""" }
         .map { s => s"{ $s, $ids }" }
         .mkString("[", ",", "]")
    
       exec("foo").post("/bar").body(_ => StringBody(data)).asJson
    

    (I added [ and ] around your generated string to make it look like valid json).

    Alternatively, you probably have some library that converts maps and lists to json out-of-the box (I don't know gatling, but there must be something), a bit cleaner way to do this would be with something like this:

        val ids = Map(
           "testId" -> "foo", 
           "typeId" ->  "bar", 
           "statusId" ->  "baz"
        )
    
        val data = (1 to 3)
         .map { _ => Random.alphanumeric.take(6).mkString }
         .map { r => ids + ("name" -> s"Perftest $r")  }
      
    
       exec("foo").post("/bar").body(_ => StringBody(toJson(data))).asJson