Check mt_rand function with PHPUnit

I would create some tests with PhpUnit. But the php file I would 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 poor English, I'm from Germany;)

+5
source share
2 answers

The Mersenne Twister algorithm is a deterministic algorithm. It starts with a seed and then generates random numbers based on this. Thus, if the seed is the same, it will generate the same random numbers.

Usually PHP seeds mt_randwith some data are based microtime, but you can manually use their seeds with mt_srand.

mt_srand(0);
var_dump(mt_rand());
mt_srand(0);
var_dump(mt_rand());

Note that both function calls will have the same number 963932192.

So, all you basically need to do is seed manually, and you can predict all the numbers that it generates.

+12
source

If you sow mt_rand each time with the same initial value, you will always get the same series of values ​​returned by mt_rand ().

eg:

mt_srand(123456);

for ($i = 0; $i < 10; $i++) {
    echo mt_rand(),'<br />';
}
0
source

All Articles