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

Viewed 38

Here is a simple test case using some global variables / constants:

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);
}

When I run this, it fails because $ONE is not initialized:

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

Why is that? Clearly the variable is defined (or I'd get an error because of the use strict;), but it seems only initialization code in the setup function runs.

How do I use constants in Test::Class tests?

1 Answers

Your assignments do get executed, but only after you finish running the tests. This is because you run the tests (call __PACKAGE__->runtests()) before the assignments.

Furthermore, you're officially not allowed to use a variable before executing its my. Your arrangement is the only thing the docs call out as undefined behaviour (meaning it can result in any behaviour).

Related