Unit testing 从测试访问perl模块中的全局

Unit testing 从测试访问perl模块中的全局,unit-testing,perl,global-variables,modulino,Unit Testing,Perl,Global Variables,Modulino,在单元测试中,我需要设置一个全局变量,该变量在perl脚本中使用,我已将其更改为modulino。我很高兴在modulino呼叫SUB 在Ubuntu上使用为x86_64-linux-gnu-thread-multi构建的perl(v5.18.2) 注意modulino非常简单,甚至不需要“caller()”技巧 test.pl #!/usr/bin/perl use strict; use warnings; my %config = ( Item => 5, ); sub

在单元测试中,我需要设置一个全局变量,该变量在perl脚本中使用,我已将其更改为modulino。我很高兴在modulino呼叫SUB

在Ubuntu上使用为x86_64-linux-gnu-thread-multi构建的perl(v5.18.2)

注意modulino非常简单,甚至不需要“caller()”技巧

test.pl

#!/usr/bin/perl
use strict;
use warnings;

my %config =
(
    Item => 5,
);

sub return_a_value{
    return 3;
}
test1.t

#!/user/bin/perl -w
use warnings;
use strict;
use Test::More;
use lib '.';
require_ok ( 'test.pl' );

print return_a_value();
test2.t

#!/user/bin/perl -w
use warnings;
use strict;
use Test::More;
use lib '.';
require_ok ( 'test.pl' );

$config{'Item'} = 6;
test1.t按预期显示

ok 1 - require 'test.pl';
3# Tests were run but no plan was declared and done_testing() was not seen
test2.t(未能编译)


正如choroba所指出的,
my
变量不是全局变量。对我来说,最好的解决方案,也是我应该首先做的,是在modulino中添加一个setter sub,类似于:

sub setItem
{
    $config{'Item'} = shift;
    return;
}
既然我现在想要一个单元测试,getter也是一个好主意

sub getItem
{
    return $config{'Item'};
}

用声明的变量不是全局变量。(SMH)谢谢!一般来说,你不应该在测试那些加载的代码的同一测试中使用require_ok,因为如果require失败,那将导致后面的测试实际上没有测试他们应该测试的内容,并且失败
sub getItem
{
    return $config{'Item'};
}