7

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

1
  • please provide a code snippet for us to see
    – Gordon
    Feb 5, 2011 at 22:45

2 Answers 2

14

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.

4
  • Thank you very much, that's exactly the answer I've been looking for!
    – Ragadabing
    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 ;)
    – NikiC
    Feb 6, 2011 at 11:01
  • Thanks, that was my first question I asked here.
    – Ragadabing
    Feb 6, 2011 at 11:14
  • 1
    Please 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
    – kioleanu
    Aug 31, 2015 at 10:30
1

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 />';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.