Testing
46.1 Test::More
# t/01-math.t
use v5.36;
use Test::More;
use lib 'lib';
use My::Math qw(add multiply);
ok(1, 'truth works');
is(add(2, 3), 5, 'add works');
isnt(add(2, 2), 5, 'add is not broken');
like('Hello Perl', qr/perl/i, 'regex match');
unlike('abc', qr/\d/, 'no digits');
is_deeply([sort 3, 1, 2], [1, 2, 3], 'deep comparison');
cmp_ok(multiply(2, 3), '>', 5, 'numeric comparison');
can_ok('My::Math', qw(add multiply));
isa_ok(Person->new(name => 'x'), 'Person');
ok(!eval { divide(1, 0); 1 }, 'dies on division by zero');
like($@, qr/zero/, 'error message mentions zero');
subtest 'edge cases' => sub {
plan tests => 2;
is(add(0, 0), 0, 'zeros');
is(add(-1, 1), 0, 'negatives');
};
SKIP: {
skip 'No network', 1 unless $ENV{NETWORK_TESTS};
ok(fetch_remote(), 'network fetch');
}
TODO: {
local $TODO = 'Not implemented yet';
ok(feature_x(), 'feature x');
}
diag 'debug info'; # printed to STDERR
note 'verbose info'; # shown with prove -v
done_testing();46.2 Test2::V0 (The Modern Suite)
use Test2::V0;
is(add(2, 3), 5, 'add');
is($user, hash {
field name => 'Ana';
field age => validator(sub { $_ > 0 });
field roles => array { item 'admin'; etc; };
end;
}, 'structure matches');
like(dies { divide(1, 0) }, qr/zero/, 'exception');
ok(lives { add(1, 1) }, 'lives');
my $mock = mock 'My::API' => (override => [fetch => sub { { status => 200 } }]);
done_testing;46.3 Running Tests and Coverage
Useful modules: Test::Exception / Test::Fatal (exceptions), Test::MockModule / Test::MockObject / Test::MockTime, Test::Deep, Test::Warnings, Test::Output, Test::Mojo (web apps), Test::DBIx::Class, Test::Perl::Critic, Test::Pod, Test::Pod::Coverage.
TAP (Test Anything Protocol), output like ok 1 - add works, originated in Perl and is used by many other languages.
prove -lv t/ # -l adds lib/ to @INC, -v verbose
prove -lr -j8 t/ # recursive, 8 parallel jobs
prove -l t/01-math.t :: --arg # pass arguments to the test
cover -test # Devel::Cover coverage report (HTML in cover_db/)
yath test -j8 # Test2::Harness runner