我开始使用Test :: More,已经有几个.t测试脚本.现在,我想定义一个仅用于测试但跨越不同.t文件的函数.哪个是放置这种功能的最佳位置?定义另一个.t而不进行任何测试,require并在需要的地方?(作为旁注,我使用Module :: Starter创建的模块结构)
rjh*_*rjh 11
最好的方法是将测试函数与任何其他函数集一样放入模块中.然后,您可以使用Test :: Builder使测试诊断/失败消息的行为就像失败源自.t文件而不是模块一样.
这是一个简单的例子.
package Test::YourModule;
use Test::Builder;
use Sub::Exporter -setup => { exports => ['exitcode_ok'] }; # or 'use Exporter' etc.
my $Test = Test::Builder->new;
# Runs the command and makes sure its exit code is $expected_code. Contrived!
sub exitcode_ok {
my ($command, $expected_code, $name) = @_;
system($command);
my $exit = $? >> 8;
my $message = $!;
my $ok = $Test->is_num( $exit, $expected_code, $name );
if ( !$ok ) {
$Test->diag("$command exited incorrectly with the error '$message'");
}
return $ok;
}
Run Code Online (Sandbox Code Playgroud)
在你的脚本中:
use Test::More plan => 1;
use Test::YourModule qw(exitcode_ok);
exitcode_ok('date', 0, 'date exits without errors');
Run Code Online (Sandbox Code Playgroud)
写一个模块,如rjh所示.把它放在t/lib/Test/YourThing.pm中,然后可以加载为:
use lib 't/lib';
use Test::YourThing;
Run Code Online (Sandbox Code Playgroud)
或者你可以把它直接放在t/Test/YourThing.pm中,调用它package t::Test::YourThing并加载它:
use t::Test::YourThing;
Run Code Online (Sandbox Code Playgroud)
好处是不必use lib在每个测试文件中写入该行,并清楚地将其标识为本地测试模块.不利的一面是混乱,如果"."它将无法正常工作.不在@INC(例如,如果您在污点模式下运行测试,但它可以解决use lib ".")并且如果您决定将.pm文件移出项目,则必须重写所有用途.你的选择.