Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test mt_rand function with PHPUnit

Tags:

php

phpunit

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 ;)

like image 873
Ragadabing Avatar asked Feb 05 '11 22:02

Ragadabing


2 Answers

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.

like image 150
NikiC Avatar answered Sep 21 '22 16:09

NikiC


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 />';
}
like image 42
Mark Baker Avatar answered Sep 22 '22 16:09

Mark Baker