davido has asked for the wisdom of the Perl Monks concerning the following question:

I find myself often including something like the following in my tests when ensuring that parameters are being validated properly, or that a subroutine is failing by throwing an exception when I expect it to:

use Test::More tests => 1; # Just for example... use Try::Tiny; my $caught; try { # Call to subroutine being tested. } catch { $caught = $_ }; ok( defined( $caught ), "tested_sub(): Threw an exception given XYZ params" ); like( $caught, qr/exception keyphrase/, "tested_sub(): Proper exception reported for xyz." );

I'm sure there is more than one way to do it, but I'm looking to see if others have a better approach. This works fine from what I can tell; at least my tests work as I expect them to. But is there already a clearer and more concise solution I should be looking at?


Dave

Replies are listed 'Best First'.
Re: Testing for exceptions with Test::More
by Your Mother (Archbishop) on Aug 19, 2011 at 21:59 UTC
Re: Testing for exceptions with Test::More
by Khen1950fx (Canon) on Aug 20, 2011 at 04:13 UTC
    I tried Test::Trap with perl5i, which has builtin support for Try::Tiny and Modern::Perl;
    #!perl use perl5i::2; use Test::More tests => 3; use Test::Trap; my $caught; my @trap = trap { some_code($caught = $_);}; is( $trap->exit, 1, 'Expecting &some_code to exit with 1' ); is( $trap->stdout, '', 'Expecting no stdout' ); like( $trap->stderr, qr/exception keyphrase/, 'tested_sub(): Expecting warnings.' );