在Test :: More中,是否有可能在末尾测试exit()的子程序?

Spe*_*mon 8 perl unit-testing perl-module

我有一个模块,我用一些实用函数编写.

其中一个函数只是一个用法语句(由用户@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;
}
Run Code Online (Sandbox Code Playgroud)

我知道子程序按预期工作,并且它很容易测试,但是...对于覆盖率报告,我想将它包含在我的单元测试中.有没有办法测试它Test::More

tin*_*ita 15

您可以使用Test :: Exit.

如果由于任何原因您无法使用它,只需复制以下代码:

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");
}
Run Code Online (Sandbox Code Playgroud)

务必在BEGIN块之后加载模块.


Cha*_*hak 2

或者,您可以使用END块来处理退出调用。

在 END 代码块内,$? 包含程序将传递给 exit() 的值。可以修改$? 更改程序的退出值。

usage();

END {
    use Test::More;
    ok($?);
    done_testing();
}
Run Code Online (Sandbox Code Playgroud)

演示: https: //ideone.com/AQx395