Part fifteen of a series of posts about automated testing.

Global state can cause problems with testing.

package Santa::Counter;

# Global state!
our $presents_delivered = 0;

sub increment {
    $presents_delivered++;
    return $presents_delivered;
}

1;

Each time this is called from tests, the result will be different:

sub counter_should_return_one {
    is(increment(), 1);
}

sub some_other_test {
    # accidentally calls increment()...
}

Depending on the order these tests get run, one will fail.

The answer is to change the code to avoid global state, and then the code can be initialized correctly for the tests.

Further reading