In Test :: More, is it possible to test a routine that will exit () at the end?

I have a module that I wrote with some useful features.

One of the functions is just a usage statement (recommended by @zdim)

use 5.008_008; use strict; use warnings; # Function Name: 'usage' # Function Inputs: 'none' # Function Returns: 'none' # Function Description: 'Prints usage on STDERR, for when invalid options are passed' sub usage ## no critic qw(RequireArgUnpacking) { require File::Basename; my $PROG = File::Basename::basename($0); for (@_) { print {*STDERR} $_; } print {*STDERR} "Try $PROG --help for more information.\n"; exit 1; } 

I know that the subroutine works as expected and is simple enough for testing, but ... For coverage reports, I would like to include it in my unit tests. Is there a way to test it with Test::More ?

+8
unit-testing perl perl-module
source share
2 answers

Alternatively, you can use END to handle exit calls.

Inside the code block END $? contains the value that the program jumps to exit (). Can you change $? change the value of the program output.

 usage(); END { use Test::More; ok($?); done_testing(); } 

Demo: https://ideone.com/AQx395

+2
source share

You can use Test :: Exit .

If for some reason you cannot use it, just copy the code below:

 our $exit_handler = sub { CORE::exit $_[0]; }; BEGIN { *CORE::GLOBAL::exit = sub (;$) { $exit_handler->(@_ ? 0 + $_[0] : 0) }; } { my $exit = 0; local $exit_handler = sub { $exit = $_[0]; no warnings qw( exiting ); last TEST; }; TEST: { # Your test here } cmp_ok($exit, '==', 1, "exited with 1"); } 

Be sure to load your module after the BEGIN block.

+15
source share

All Articles