I would create some tests with PhpUnit. But the php file which I'd like to test uses the mt_rand() function. So how can I create a test that knows the value of mt_rand () returns the last time? Thank you for answering my question and sorry for my bad English, I'm from Germany ;)
The Mersenne Twister algorithm is a deterministic algorithm. It starts off with a seed and then generates random numbers based on it. Thus, given the seed is the same, it will generate the same random numbers.
Normally PHP seeds mt_rand
with some microtime
based data, but you can manually seed it using mt_srand
.
mt_srand(0);
var_dump(mt_rand());
mt_srand(0);
var_dump(mt_rand());
Note that both function calls will give you the same number 963932192
.
So all you basically have to do, is seed it manually and you will be able to predict all numbers it generates.
If you seed mt_rand with the same seed value every time, you'll always get the same series of values returned by mt_rand().
for example:
mt_srand(123456);
for ($i = 0; $i < 10; $i++) {
echo mt_rand(),'<br />';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With