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 ;)
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.
-
Thank you very much, that's exactly the answer I've been looking for! Feb 6, 2011 at 10:23
-
@Paloran: If that's the answer you were looking for, click on the green tick to the left of the answer ;)– NikiCFeb 6, 2011 at 11:01
-
-
1Please note that this answer is no longer valid. In PHP 5.2.1 the Mersenne Twister algorithm implementation has been changed and sequences with the same seed no longer produce the same numbers. My suggestion now is to move the mt_rand call into a separate class/method and mock the return value using the php unit mock class– kioleanuAug 31, 2015 at 10:30
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 />';
}