Test::Exception average
We have a function to calculate the average of the given numbers.
If we are not careful, the user might call it with an empty list of values. In that case we would try to divide by 0. That would result in an “Illegal division by zero” exception.
That can be confusing. It would be much better to tell the user parameters were missing.
package MyMath;
use strict;
use warnings;
sub average {
#@_ or die "Missing parameters";
#die "Missing parameters" if not @_;
#if (0 == scalar @_) {
# die "Missing parameters";
#}
my $sum = 0;
for my $val (@_) {
$sum += $val;
}
return $sum / scalar @_;
}
1;
use strict;
use warnings;
use feature 'say';
use lib 'lib';
use MyMath;
say MyMath::average(@ARGV);
use strict;
use warnings;
use lib 'lib';
use MyMath;
use Test::More;
use Test::Exception;
is MyMath::average(1, 1), 1;
is MyMath::average(1, 2, 3), 2;
throws_ok { MyMath::average() } qr/Illegal division by zero/, 'missing parameter';
#throws_ok { MyMath::average() } qr/Missing parameters/, 'missing parameter';
#is MyMath::average("abc", "def"), 0;
#We might want the average function to rais an exception when strings were given.
#or we might decide to treat them as 0
#or as hexadecimal values
#or ....
done_testing;