Manual mock random generator in BEGIN block
Through the CORE namespace we can replace the rand function to our implementation.
In this implementation we prepare 2 values to be returned when the rand function is called anywhere in the process.
That means both in the dice function and elsewhere. So our manual mocking has a global impact. It is usable, but maybe not ideal.
We need to do it in the BEGIN block before we use the MyRandomApp so it will take effect there.
use strict;
use warnings;
use 5.010;
BEGIN {
my @values = (0.03, 0.72);
*CORE::GLOBAL::rand = sub {
return shift @values;
};
}
use Test::More;
use MyRandomApp qw(dice);
is dice(10), 1;
is dice(10), 8;
my $x = rand();
is $x, undef, 'We have replaced rand here too';
done_testing;
prove -lv t/test-begin.t