ZetCode

Perl Test::More

last modified November 25, 2026 Perl 5.44

Test::More is the standard module for writing tests in Perl. It ships with Perl, so no installation is needed. A test is an ordinary Perl program that checks results with functions such as ok and is. Each check prints one line in the Test Anything Protocol (TAP), a simple text format that tools such as prove read and summarize.

By convention, test files have the .t extension and live in a t directory next to the code they test. They can be run with perl like any other script.

A first test with ok

The simplest check is ok. It passes when its first argument is true. The tests option in the use line declares how many checks the program will run. This declaration is called the plan.

first.t
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Test::More tests => 2;

my @langs = qw(Perl Python Ruby);

ok(@langs == 3, 'three languages');
ok(grep({ $_ eq 'Perl' } @langs), 'Perl is in the list');

The first check compares the size of the array with 3. The second one uses grep to find Perl in the list. The optional second argument of ok is a description that appears in the output. The first output line, 1..2, is the plan. Then every check prints ok with its number and description.

$ perl first.t
1..2
ok 1 - three languages
ok 2 - Perl is in the list

Comparing values with is and isnt

ok only knows whether a check passed. When a comparison fails, it cannot say what the actual value was. The is function takes the value we got and the value we expected and compares them as strings with eq. isnt passes when the two values differ.

is_isnt.t
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Test::More tests => 4;

sub add { return $_[0] + $_[1] }

is(add(2, 3), 5, 'two positive numbers');
is(add(-1, 1), 0, 'negative and positive');
isnt(add(1, 1), 3, 'one plus one is not three');
is(uc 'perl', 'PERL', 'uc converts to upper case');

The program tests a small add function and the built-in uc. Numbers are compared as strings too, which works for integers like these. All four checks pass.

$ perl is_isnt.t
1..4
ok 1 - two positive numbers
ok 2 - negative and positive
ok 3 - one plus one is not three
ok 4 - uc converts to upper case

Reading a failing test

A test is only useful when its failures are easy to read. In the next program, one of the expectations is wrong on purpose.

failing.t
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Test::More tests => 3;

sub area { return $_[0] * $_[1] }

is(area(3, 4), 12, 'area of 3x4');
is(area(2, 5), 12, 'area of 2x5');
is(area(0, 9), 0, 'zero width');

For a failed check, Test::More prints not ok, followed by comment lines that start with #. They give the description, the file and line, and the values that is got and expected. The diagnostics go to standard error, while the ok lines go to standard output.

At the end, the module reports the number of failures and uses it as the exit status of the program. A build script or a continuous integration system can detect the failure from the exit status alone.

$ perl failing.t
1..3
ok 1 - area of 3x4
not ok 2 - area of 2x5
#   Failed test 'area of 2x5'
#   at failing.t line 10.
#          got: '10'
#     expected: '12'
ok 3 - zero width
# Looks like you failed 1 test of 3.
$ echo $?
1

Patterns and numeric comparisons

Some results cannot be compared with a single exact value. The like function checks a string against a regular expression and unlike checks that it does not match. cmp_ok takes an operator, so it can compare numbers with <, == or any other binary operator.

like_cmp.t
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Test::More tests => 5;

my $greeting = 'Hello there, Lucia!';

like($greeting, qr/^Hello/, 'starts with Hello');
like($greeting, qr/Lucia/, 'mentions Lucia');
unlike($greeting, qr/\d/, 'contains no digits');

my $elapsed = 0.42;

cmp_ok($elapsed, '<', 1, 'finished within a second');
cmp_ok(length $greeting, '==', 19, 'greeting length');

The patterns are given as qr// objects. The first cmp_ok checks that a measured time is under a limit, which is could not express. When cmp_ok fails, its diagnostic shows both operands and the operator.

$ perl like_cmp.t
1..5
ok 1 - starts with Hello
ok 2 - mentions Lucia
ok 3 - contains no digits
ok 4 - finished within a second
ok 5 - greeting length

Comparing data structures with is_deeply

is cannot compare arrays or hashes. Given two references, it compares their addresses, which differ even for identical contents. The is_deeply function walks both structures and compares them element by element.

deeply.t
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Test::More tests => 3;

my @doubled = map { $_ * 2 } 1 .. 3;
is_deeply(\@doubled, [2, 4, 6], 'doubling a list');

my %user = (name => 'Lucia', roles => ['admin', 'dev']);
is_deeply(\%user, { name => 'Lucia', roles => ['admin', 'dev'] },
    'user record');

my %copy = (name => 'Lucia', roles => ['admin', 'ops']);
is_deeply(\%copy, \%user, 'copied user record');

The first two checks pass. In the third one, the copy has a different second role. The diagnostic points to the exact place where the structures begin to differ, written as a Perl expression: $got->{roles}[1].

$ perl deeply.t
1..3
ok 1 - doubling a list
ok 2 - user record
not ok 3 - copied user record
#   Failed test 'copied user record'
#   at deeply.t line 15.
#     Structures begin differing at:
#          $got->{roles}[1] = 'ops'
#     $expected->{roles}[1] = 'dev'
# Looks like you failed 1 test of 3.

Table-driven tests and done_testing

Many tests run the same check on a list of inputs. The number of checks then depends on the data, and counting them by hand for the plan is error-prone. Instead, the program can leave the plan out and call done_testing at the end.

table.t
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Test::More;

sub is_leap {
    my ($y) = @_;
    return ($y % 4 == 0 && $y % 100 != 0) || $y % 400 == 0 ? 1 : 0;
}

my @cases = (
    [2024, 1], [2023, 0], [1900, 0], [2000, 1],
);

for my $case (@cases) {
    my ($year, $expected) = @$case;
    is(is_leap($year), $expected, "leap year check for $year");
}

done_testing();

Each case is an array reference with a year and the expected result. The loop runs one is check per case. done_testing prints the plan after the last check, so it appears at the end of the output. If the program dies before reaching done_testing, the missing plan marks the run as failed.

$ perl table.t
ok 1 - leap year check for 2024
ok 2 - leap year check for 2023
ok 3 - leap year check for 1900
ok 4 - leap year check for 2000
1..4

Grouping checks with subtests

A subtest groups related checks under one name. The group counts as a single check in the parent test, and it passes only when all checks inside it pass.

subtests.t
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Test::More;

sub trim {
    my ($s) = @_;
    $s =~ s/^\s+|\s+$//g;
    return $s;
}

subtest 'leading and trailing spaces' => sub {
    is(trim('  perl'), 'perl', 'leading');
    is(trim('perl  '), 'perl', 'trailing');
    is(trim('  perl  '), 'perl', 'both');
};

subtest 'inner spaces' => sub {
    is(trim('a b'), 'a b', 'single inner space kept');
    is(trim(' a  b '), 'a  b', 'double inner space kept');
};

done_testing();

The program tests a trim function in two groups. The output of each subtest is indented and ends with its own plan. Then the parent prints one ok line for the whole group.

$ perl subtests.t
# Subtest: leading and trailing spaces
    ok 1 - leading
    ok 2 - trailing
    ok 3 - both
    1..3
ok 1 - leading and trailing spaces
# Subtest: inner spaces
    ok 1 - single inner space kept
    ok 2 - double inner space kept
    1..2
ok 2 - inner spaces
1..2

Testing exceptions

Code should also be tested for the way it fails. A function that dies on bad input can be called inside eval, and the error message in $@ can then be checked with like. The eval block is described in Perl error handling.

exceptions.t
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Test::More;

sub divide {
    my ($x, $y) = @_;
    die "division by zero\n" if $y == 0;
    return $x / $y;
}

is(divide(10, 4), 2.5, 'normal division');

my $ok = eval { divide(1, 0); 1 };
ok(!$ok, 'dividing by zero dies');
like($@, qr/division by zero/, 'error message');

$ok = eval { divide(1, 2); 1 };
ok($ok, 'valid division does not die');

done_testing();

The eval block returns 1 only when divide returns normally. For a zero divisor it dies, so $ok is false and $@ holds the message. The last check makes sure that a valid call does not die.

$ perl exceptions.t
ok 1 - normal division
ok 2 - dividing by zero dies
ok 3 - error message
ok 4 - valid division does not die
1..4

Skipping tests and TODO tests

Some checks make sense only in certain environments, and some describe features that are not finished yet. A SKIP block skips checks that cannot run. A TODO block runs checks that are expected to fail, without failing the whole test.

skip_todo.t
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Test::More;

SKIP: {
    skip 'not running on Windows', 1 if $^O ne 'MSWin32';

    ok(-e 'C:/Windows', 'Windows directory exists');
}

TODO: {
    local $TODO = 'title case not implemented yet';

    is(ucfirst 'the perl book', 'The Perl Book', 'title case');
}

note "running on $^O";
diag 'diag messages go to standard error';

ok(1, 'last test');

done_testing();

The skip function takes a reason and the number of checks to skip. It leaves the SKIP block at once and prints an ok line with # skip for each skipped check. Inside the TODO block, the $TODO variable holds the reason. The failing check is marked # TODO, and the program still exits with status 0.

The note and diag functions print comments. The difference is where they go: note writes to standard output and diag to standard error. The prove program shows diag messages always and note messages only in verbose mode.

$ perl skip_todo.t
ok 1 # skip not running on Windows
not ok 2 - title case # TODO title case not implemented yet
#   Failed (TODO) test 'title case'
#   at skip_todo.t line 16.
#          got: 'The perl book'
#     expected: 'The Perl Book'
# running on linux
# diag messages go to standard error
ok 3 - last test
1..3

Testing a module with prove

In a real project, the code lives in modules under lib and the tests under t. The following module converts temperatures. Modules and Exporter are covered in Perl packages.

lib/Temperature.pm
package Temperature;

use strict;
use warnings;

use Exporter 'import';
our @EXPORT_OK = qw(c_to_f f_to_c);

sub c_to_f {
    my ($c) = @_;
    return $c * 9 / 5 + 32;
}

sub f_to_c {
    my ($f) = @_;
    return ($f - 32) * 5 / 9;
}

1;

The module exports its two functions only on request, through @EXPORT_OK.

t/temperature.t
use warnings;
use v5.34.0;
use Test::More;

use_ok('Temperature', qw(c_to_f f_to_c));
can_ok('Temperature', qw(c_to_f f_to_c));

is(c_to_f(100), 212, 'boiling point');
is(c_to_f(-40), -40, 'scales meet at -40');
is(f_to_c(32), 0, 'freezing point');

for my $c (-10, 0, 37) {
    is(f_to_c(c_to_f($c)), $c, "round trip for $c");
}

done_testing();

use_ok loads the module and imports the listed functions. It is a check of its own, so a module that fails to compile is reported as a failed test. can_ok verifies that the package has the given functions. The loop converts a few values there and back.

The prove program, which comes with Perl, runs test files and summarizes the results. The -l option adds lib to the module search path and -v prints the output of every check.

$ prove -l -v t/temperature.t
t/temperature.t .. 
ok 1 - use Temperature;
ok 2 - Temperature->can(...)
ok 3 - boiling point
ok 4 - scales meet at -40
ok 5 - freezing point
ok 6 - round trip for -10
ok 7 - round trip for 0
ok 8 - round trip for 37
1..8
ok
All tests successful.
Files=1, Tests=8,  0 wallclock secs ( 0.01 usr  0.00 sys +  0.02 cusr  0.00 csys =  0.03 CPU)
Result: PASS

Without -v, prove prints one line per file. Given a directory, it runs every .t file in it.

$ prove -l t
t/temperature.t .. ok
All tests successful.
Files=1, Tests=8,  0 wallclock secs ( 0.01 usr  0.00 sys +  0.02 cusr  0.00 csys =  0.03 CPU)
Result: PASS

Best practices

Keep these points in mind when writing tests with Test::More.

Source

Test::More · prove · Test Anything Protocol

In this article we have written tests with ok, is, like, cmp_ok and is_deeply, used done_testing, subtests, skipped and TODO tests, tested exceptions and run a module's test suite with prove. See also Perl packages and Perl error handling.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Perl tutorials.