从测试中访问 perl modulino 中的全局
Accessing a global in a perl modulino from a test
在单元测试中,我需要设置一个在我已更改为 modulino 的 perl 脚本中使用的全局变量。我很高兴在 modulino 中调用 subs。
使用为 x86_64-linux-gnu-thread-multi 构建的 perl (v5.18.2),在 Ubuntu。
请注意模数非常简单,甚至不需要 "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(编译失败)
Global symbol "%config" requires explicit package name at test.t line 8.
Execution of test.t aborted due to compilation errors.
正如 choroba 所指出的,my
变量不是全局的。对我来说最好的解决方案,也是我一开始应该做的是在模数中添加一个 setter sub,比如:
sub setItem
{
$config{'Item'} = shift;
return;
}
因为我现在想要一个单元测试,getter 也是一个好主意
sub getItem
{
return $config{'Item'};
}
在单元测试中,我需要设置一个在我已更改为 modulino 的 perl 脚本中使用的全局变量。我很高兴在 modulino 中调用 subs。
使用为 x86_64-linux-gnu-thread-multi 构建的 perl (v5.18.2),在 Ubuntu。
请注意模数非常简单,甚至不需要 "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(编译失败)
Global symbol "%config" requires explicit package name at test.t line 8.
Execution of test.t aborted due to compilation errors.
正如 choroba 所指出的,my
变量不是全局的。对我来说最好的解决方案,也是我一开始应该做的是在模数中添加一个 setter sub,比如:
sub setItem
{
$config{'Item'} = shift;
return;
}
因为我现在想要一个单元测试,getter 也是一个好主意
sub getItem
{
return $config{'Item'};
}