I’m currently trying to learn unit testing. To do this I’m writting a script at work, and I’m creating unit tests for the entire script. Thus far things have been going well, but I’m trying to test that incorrect data entered into the script form the command line triggers a help message.
My code looks something like:
sub getContext{
my ($help) = @_;
GetOptions(
help|h => \$help,
...
pod2usage if $help;
...
}
My tests look something like:
my $help_exception = 0;
try{
getContext( {help => 0} );
}catch{
$help_exception = 1;
}
ok($help_exception, "Script died correctly when given help flag");
My output looks very similar to:
1..4
ok 1 - use scripts::scriptname;
ok 2
ok 3
# Looks like you planned 4 tests but ran 3.
# Looks like your test exited with 1 just after 3.
The test for the help flag is test 4, it looks like my script is exiting without triggering the Try::Tiny try catch block. Is there a way to fix this, or should I be writing my tests differently?
Pod::Usage‘s documentation for it’s-exitvalargument shows how to stop it from exiting all together. You could simply use that and adapt your code and/or tests accordingly.Otherwise,
exitis not an exception, and therefore not trappable like an exception. However, it is overridable throughCORE::GLOBAL::exit. Using that is a reasonable approach as well, assuming your properly localise your modifications.Alternatively, you can always just start a subprocess to run your entire script and capture what it does, basing your tests on that, entirely avoiding the problem of
Pod::Usagecallingexit.On a related note, the way you’re using
Try::Tinyin your test is a bit odd. I believe usingTest::Fatal(which is based onTry::Tiny) might make for clearer tests in the future.