2.2. Demo

Let's suppose we want to test a function that adds two numbers. (This is a classic example.) We have the following function in the module Add1.pm:

package Add1;

use strict;
use warnings;

use vars qw(@EXPORT_OK @ISA);

use Exporter;

@ISA = (qw(Exporter));

@EXPORT_OK = (qw(add));

sub add
{
    my $x = shift;
    my $y = shift;

    return 4;
}

1;

One way to write a rudimentary script to test it, would be the following:

#!/usr/bin/perl

use strict;
use warnings;

use Add1 (qw(add));

if (!(add(2,2) == 4))
{
    die "add(2,2) failed";
}
exit(0);

This script will die with an ugly exception if adding 2 and 2 failed and quietly exit with a success code if everything is OK. Let's run it:

$ perl add1-test.pl
$

Everything is OK. Now let's write another test:

#!/usr/bin/perl

use strict;
use warnings;

use Add1 (qw(add));

if (!(add(2,2) == 4))
{
    die "add(2,2) failed";
}

{
    my $result = add(1,1);

    if ($result != 2)
    {
        die "add(1,1) resulted in '$result' instead of 2."
    }
}

exit(0);

This time the test fails:

$ perl add1-test-2.pl
add(1,1) resulted in '4' instead of 2. at add1-test-2.pl line 18.
$

As a result, we need to fix the production code:

package Add2;

use strict;
use warnings;

use vars qw(@EXPORT_OK @ISA);

use Exporter;

@ISA = (qw(Exporter));

@EXPORT_OK = (qw(add));

sub add
{
    my $x = shift;
    my $y = shift;

    return $x+$y;
}

1;

And the equivalent test script is successful:

#!/usr/bin/perl

use strict;
use warnings;

use Add2 (qw(add));

if (!(add(2,2) == 4))
{
    die "add(2,2) failed";
}

{
    my $result = add(1,1);

    if ($result != 2)
    {
        die "add(1,1) resulted in '$result' instead of 2."
    }
}

exit(0);

Now we can continue writing more tests, and see that they passed.


Written by Shlomi Fish