我开始使用Test::More,已经有几个.t测试脚本。现在,我想定义一个仅用于测试但跨越不同.t文件的函数。哪个是放置这种功能的最佳位置?在没有任何测试的情况下定义另一个.t并在需要时require
定义它(作为旁注,我使用Module::Starter创建的模块结构)
答案 0 :(得分: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;
}
在你的剧本中:
use Test::More plan => 1;
use Test::YourModule qw(exitcode_ok);
exitcode_ok('date', 0, 'date exits without errors');
答案 1 :(得分:9)
写一个模块,如rjh所示。把它放在t / lib / Test / YourThing.pm中,然后可以加载为:
use lib 't/lib';
use Test::YourThing;
或者你可以把它直接放在t / Test / YourThing.pm中,称之为package t::Test::YourThing
并将其加载为:
use t::Test::YourThing;
优点是不必在每个测试文件中写入use lib
行,并清楚地将其标识为本地测试模块。不利的一面是混乱,如果“。”它将无法正常工作。不在@INC
中(例如,如果您在污点模式下运行测试,但它可以与use lib "."
一起使用),如果您决定将.pm文件移出项目,则重写所有用途。你的选择。