Testing for warnings

Test code that should give a warning, and check if that is the correct warning.

So once we have tested our nicely behaving code we can also test our warnings and errors. For this we are going to use several additional modules from CPAN. As they all use the Test::Builder backend we can use them along with our standard Test::More setup.

use strict;
use warnings;

use Test::More;
use Test::Warn;

use MyTools qw(fibo);

subtest negative => sub {
    my $result = 'something else';
    warning_is {$result = fibo(-1)} "Given number must be > 0",
        'warning when called with -1';
    is($result, undef, 'fibonacci on -1 returns undef');


prove -lv t/fibonacci_negative_tested.t

t/fibonacci_negative_tested.t .. 
# Subtest: negative
    ok 1 - warning when called with -1
    ok 2 - fibonacci on -1 returns undef
ok 1 - negative
All tests successful.
Files=1, Tests=1,  1 wallclock secs ( 0.02 usr  0.00 sys +  0.16 cusr  0.02 csys =  0.20 CPU)
Result: PASS