A new must use module - Test::Exception

I write quite a few unit tests that have methods or subs that throw exceptions (like most good code should... this rule has numerous good exceptions! hahaha, sorry couldn't resist.). A few months ago I ran across Test::Exception.

In the past I would often write unit tests for these cases like:
{
my $err;
my $obj;

eval { $obj = MyObject->new; };

## constructor expected to fail
$err = $@;
ok $err, "constructor - missing parameters";

## or for methods that aren't suppose to throw
eval { $obj = MyObject->new( server => 'localhost' ) };

## check constructor
$err = $@;
ok !$err, "constructor";
isa_ok $obj, 'MyObject';
}
This construct became very tiring, verbose and distracts from what is really going on. (Yuck!)

With Test::Exception, I can convert these annoying eval blocks into nicely contain lines.

Example from above:
use Test::Exception;

{
my $obj;

throws_ok { $obj = MyObject->new; } qr/Error Message to match/,
'constructor - missing parameters';

lives_ok { $obj = MyObject->new( server => 'localhost' ) } "constructor";
isa_ok $obj, 'MyObject';
}
The only thing that is a bit of a syntax gotcha is that the lives_ok requires a parameters of 'block "string"'. Notice that missing comma, odd but it is much better than my previous eval crap.

Test::Exception really makes this better, thanks to the author.

Comments

  1. May be you will be interested in my blog entry about testing - http://blogs.perl.org/users/alexey_shrub/2011/02/non-functional-perl-code-testing---automated-code-review.html

    ReplyDelete

Post a Comment

Popular posts from this blog

Template Toolkit Debugging inside of Perl Dancer

BootstrapX clickover

Changing Dancer::Plugin::Ajax's content type