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
callerfunction 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,
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
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.
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.