O'Reilly logo

Intermediate Perl by Tom Phoenix, brian d foy, Randal L. Schwartz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Writing Tests with Test::More

The Test::More [*] module comes with the standard Perl distribution starting with Perl 5.8, and it's available on CPAN if we need to install it on earlier Perl versions. It works all the way back to perl5.6, at least. We rewrite the tests from the previous section (and throw in a couple more) in this test script, which uses the ok( ) function from Test::More.

use Test::More tests => 4;

ok(1 + 2 =  = 3, '1 + 2 =  = 3');
ok(2 * 4 =  = 8, '2 * 4 =  = 8');
my $divide = 5 / 3;
ok(abs($divide - 1.666667) < 0.001, '5 / 3 =  = (approx) 1.666667');
my $subtract = -3 + 3;
ok(($subtract eq '0' or $subtract eq '-0'), '-3 + 3 =  = 0');

The ok( ) function prints "ok" if its first argument is true, and "not ok" otherwise. The optional second argument lets us name the test. After the initial output to indicate success, ok( ) adds a hyphen and then the name of the test. When we find a test that does not work, we can find it by the name that we gave it.

1..4
ok 1 - 1 + 2 =  = 3
ok 2 - 2 * 4 =  = 8
ok 3 - 5 / 3 =  = (approx) 1.666667
ok 4 - -3 + 3 =  = 0

Now Test::More does all of the hard work. We don't have to think about the output or the test numbering. But what about that nasty little 4 constant in the first line? That's fine once we're shipping the code, but while we're testing, retesting (retesting some more), and adding more tests, we don't want to keep updating that number to keep the test harness from complaining about too many or too few tests. We change that to no_plan ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required