1
votes

I am new in Gatling and Scala. Sending Get Request the response body is Array and I need to extract only one object from Array and post it in Gatling. Can someone explain to me how to do it?

Here is my code example:

private val getUsers = exec(
      http("Get users")
        .get("/users")
        .check(status.is(200))
        .check(bodyString.saveAs("Users")))

The result that I get is:

[{"id":"1","hairColor":"BROWN","age":24,"language":"English","birthDate":"1995-02-10"},
{"id":"2","hairColor":"YELLOW","age":30,"language":"Australian","birthDate":"1889-10-05"},
{"id":"3","hairColor":"BLACK","age":15,"language":"American","birthDate":"..."},
{"id":"4","hairColor":"RED","age":50,"language":"Russian","birthDate":"..."}]

How to get whatever only one User from this array and post entire User object?

3
Have you tried this already? stackoverflow.com/questions/42277962/… - jPO
@jPO yes, I was looking at this example but it didn't help me to solve mine problem. My example is different. - aliiise
when you say 'one user', do you want just the id, or do you need to submit the entire json object for a user? - James Warr
@JamesWarr I would like to submit the entire json object for user - aliiise

3 Answers

3
votes

if you switch to a jsonPath check, you can get all the user objects into a Vector which has some nice support in the Gatling EL

so instead of

.check(bodyString.saveAs("Users"))

you can use

.check(jsonPath("$..[?(@.id)]").findAll.saveAs("Users")))

then when you come to make your subsequent calls, you can do things like

select the 1st user with

.body(StringBody("${Body(1).jsonStringify()}"))

select a random user with

.body(StringBody("${Body.random().jsonStringify()}"))

This approach will also allow you to use .forEach to interate over all the records

2
votes

I found an answer by myself. If I want to save whatever one object from array I can do this ->

private val getUsers = exec(
  http("Get users")
    .get("/users")
    .check(status.is(200))
    .check(jsonPath("$[0]").find.saveAs("user")))

Of course, I have to specify which value I want to save but in my example, I am saving the first value. And later you can use this value for other requests.

1
votes

You can easy get, but you need define which key

Its example where I used 'id' by the key

$.[*].[?(@.id == '1')]


$.[*] <= get all elem of array

.[?(@.id == '1')] <= get element which id equals to '1' (you can use any value).

Or any key $.[*].[?(@.hairColor == 'BROWN')]


Then just add .check(jsonPath("$.[*].[?(@.id == '1')]").saveAs("myUser")