ado
ado

Reputation: 1471

How to test that a method generating random numbers does generate random numbers

How can I test that a method generating random numbers actually generates random numbers? Is there some ($tested_method, rand) sort of syntax?

Specifically, I'm referring to this ping generator method:

sub _create_ping_number {
   my ( $ping, @random_array );
   my $MAX            = 100000;
   my $random_counter = 0;

   if ( $random_counter == $MAX ) {
     @random_array   = ();
     $random_counter = 0;
   }

   until ( !undef( $random_array[ $ping = int( rand($MAX) ) ] ) ) { }
      $random_array[$ping] = 1;
      $random_counter++;
      return $ping;
}

Upvotes: 2

Views: 159

Answers (1)

Neil Slater
Neil Slater

Reputation: 27207

The links in comment by mob provide much detail on how difficult it is to assert that a data source is random.

For your unit test, you may be better off using srand in the test setup (making this technically a "white box" test), and relying on the fact that behaviour of rand() is well known. This is normal practice as far as I know, unless you want to test a PRNG or entropy source that you have written.

Upvotes: 1

Related Questions