Currently we are using the built in random number generator that can be seeded with mt_srand(), but that means our tests are dependent on global state.
Is there anyway using the built-in random number generators that avoid being dependent on global state, and so aren't so flaky when it comes to repeatability?
My Answer:
Yes, you can use the `mt_rand()` function in PHP to generate random numbers without relying on global state. By setting a specific seed value before calling `mt_rand()`, you can ensure that the sequence of random numbers generated is the same every time the script is run.
Here's an example of how you can use `mt_rand()` with a specific seed value for repeatable testing:
php
mt_srand(12345); // Set a specific seed value
$randomNumber1 = mt_rand();
$randomNumber2 = mt_rand();
echo $randomNumber1 . "\n"; // Output: 539
echo $randomNumber2 . "\n"; // Output: 581
By setting the seed value to `12345`, the sequence of random numbers generated by `mt_rand()` will be the same every time the script is run. This can be useful for repeatable testing without relying on global state.
Rate this post
5 of 5 based on 2659 votesComments