Issue: Same Random number set for different Iterations and different users

Hi All,

Statement:
I have a scenario, where I need to randomly execute either one of the two scenarios based on the below condition.

.doIfOrElse( (rand.rand()) % 2 == 0)
(scenario1)
(scenario2)

I have written a separate class for the random number generation

import scala.util.Random._

object rand {
def rand(): Int = {
var Sum: Int = nextInt(100)
return Sum
}
}

Problem:

For all the Users and iterations the random number which is set at first is being used throughout the test.

I have checked var is mutable and also found that if var is initialized first it will be used throughout the test.

My desired output:

for 1st iteration
rand number = 5
execute scenario 2

for 2nd iteration
rand number = 6
execute scenario 1

Regards,
Aravind Ganesan

This is explained in the doc and demoed in the tutorials: https://gatling.io/docs/current/advanced_tutorial/#step-05-check-and-failure-management

If you want to pass a piece of code that gets evaluated every time a virtual user goes through this step, you have to pass a function.

Hi Stephane,

Thanks for the quick response. Please tell if the below is correct.

function to generate random number

import java.util.concurrent.ThreadLocalRandom

object rand {
def rand(): Int = {
var Sum: Int = ThreadLocalRandom.current.nextInt(100)
return Sum
}
}

object A {

doIfOrElse( (rand.rand()) % 2 == 0)
(scenario1)
(scenario2)

}

// Scenario1 & 2 defined separately.

So when I execute the above code will I get different random number for each iteration and Vusers?

Thanks in Advance.

I tried passing it as function even then the same random number is set for all the Vusers and the same scenario is getting executed depending on the random number initially set. Kindly help on this Stephane.

No, this is not passing a function, this is calling a method to pass a value.
Please properly read the example I provided.

Hi Stephane,

I am sorry, I couldn’t figure this I went through your examples as well many times. If possible could you give a custom example for this.
I know this is really simple but I am really struck on this. It will be helpful if you could say in much simpler terms.

Regards,
Aravind

Doc (https://gatling.io/docs/current/advanced_tutorial/#step-05-check-and-failure-management):

status.is(session => 200 + ThreadLocalRandom.current.nextInt(2))

Really thanks a lot Stephane. It is working :).