为什么我的全局变量没有在 Test::Class 中初始化?

Why do my global variables don't get initialized in Test::Class?

这是一个使用一些全局变量/常量的简单测试用例:

use strict;
use warnings;
use base 'Test::Class';
use Test::More;

__PACKAGE__->runtests() unless caller;

my $ONE = "1";
my $TWO;

sub setup : Test(setup) {
    $TWO = "2";
}

sub test_me : Tests {
    is("1", $ONE);
    is("2", $TWO);
}

当我 运行 这个时,它失败了,因为 $ONE 没有初始化:

robert@saaz:~$ prove test.t 
test.t .. 1/? 
#   Failed test 'test me'
#   at test.t line 16.
#   (in main->test_me)
#          got: '1'
#     expected: undef
# Looks like you failed 1 test of 2.
test.t .. Dubious, test returned 1 (wstat 256, 0x100)
Failed 1/2 subtests 

Test Summary Report
-------------------
test.t (Wstat: 256 Tests: 2 Failed: 1)
  Failed test:  1
  Non-zero exit status: 1
Files=1, Tests=2,  0 wallclock secs ( 0.02 usr  0.00 sys +  0.05 cusr  0.00 csys =  0.07 CPU)
Result: FAIL

这是为什么?显然变量已定义(或者我会因为 use strict; 而出错),但它似乎只是设置函数 运行s.

中的初始化代码

如何在 Test::Class 测试中使用常量?

您的作业确实会执行,但只有在您完成 运行测试之后。这是因为您 运行 在作业之前进行了测试(调用 __PACKAGE__->runtests())。

此外,官方不允许在执行变量 my 之前使用变量。您的安排是文档唯一指出的未定义行为(这意味着它可能导致任何行为)。