Testing with Test::More
| The first test file | |
| Assertions | |
| Run with prove | |
| Test layout |
The first test file
Test::More ships with Perl, so a test suite needs no install. A test file is a normal Perl program that prints one line per check and finishes with a plan.
t/basic.t
use strict;
use warnings;
use Test::More tests => 3;
is(2 + 2, 4, "addition works");
ok(1, "truth is true");
like("error 42", qr/\d+/, "finds digits");
ok 1 - addition works ok 2 - truth is true ok 3 - finds digits 1..3
The plan at the top states how many tests will run. done_testing() at the bottom is the modern alternative when you do not want to count.
Assertions
Test::More has a function for every common comparison, and each one prints a useful diff on failure. Pick the most specific function available instead of wrapping everything in ok.
is_deeply([1, 2], [1, 2], "lists match");
cmp_ok(10, '>', 5, "bigger");
isnt(1, 2, "different");
unlike("clean", qr/error/, "no errors");
For code that should die, use a block plus like on $@. For code that should not, wrap it and fail if $@ is set.
eval { die "boom\n" };
like($@, qr/boom/, "dies with boom");
Run with prove
prove is the standard runner. Give it the folder and it finds every .t file, runs each in its own process, and prints one summary line per file.
prove -l t/
t/basic.t .. ok All tests successful. Files=1, Tests=3, 0 wallclock secs
The -l flag adds the lib folder to the search path, so tests can load the module under test without an install step. Add -v when a single test needs to explain itself.
Test layout
The layout that CPAN expects works for private projects too. One module, one test file, named after the module with the same path inside t.
project/ ├── lib/My/Text.pm ├── t/basic.t ├── cpanfile └── Makefile.PL
When a test fails, run that file alone with perl and read the diff. The failure message names the expected and the received value, which is usually enough to find the bug without a debugger.
Next: strict, warnings and diagnostics
Article author: Arthur Isaev