DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for The attraction of Test::Fatal in Perl
Mark Gardner
Mark Gardner

Posted on • Originally published at phoenixtrap.com on

The attraction of Test::Fatal in Perl

In February I wrote an article surveying exception handling in Perl, recommending that developers use Test::Exception to make sure their code behaves as expected. A commenter on Reddit suggested I check out Test::Fatal as an alternative. What advantages does it hold over Test::Exception?

  • It only exports one function compared to Test::Exception’s four: exception, which you can then use with the full suite of regular Test::More functions as well as other testing libraries such as Test::Deep.
  • It doesn’t override the caller function or use Sub::Uplevel to hide your test blocks from the call stack, so if your exception returns a stack trace you’ll get output from the test as well as the thing throwing the exception. The author considers this a feature since Sub::Uplevel is β€œtwitchy.”

To ease porting, Test::Fatal also includes two functions, dies_ok and lives_ok, replacing Test::Exception’s functions of the same names. dies_ok does not provide the exception thrown, though, so if you’re testing that you’ll need to use exception along with a TAP-emitting function like is() or like().

And that’s it! Either is a valid choice; it comes down to whether you prefer one approach over another. Test::Exception is also included as part of Test::Most’s requirements, so if you’re using the latter to reduce boilerplate you’ll be getting the former.

Postscript:

I’d be remiss if I didn’t also mention Test2::Tools::Exception, which is the preferred way to test exceptions using the Test2 framework. If you’re using Test2, ignore all the above and go straight to Test2::Tools::Exception.

Top comments (0)

Let's team up together 🀝

We're Hiring

We're hiring for a Senior Full Stack Engineer to join the DEV team. Want the deets? Head here to learn more about who we're looking for.