PHPUnit 4.6 and Global State

PHPUnit 4.6, which was released last week, introduces an optional check that marks a test as risky when global variables, super-global variables, or static attributes in user-defined classes are modified during its execution.

1 2 3 4 5 6 7 8 9 10 11 12 13 14
class ExampleClass
public function doSomething ( )
// ...

$GLOBALS [ 'foo' ] = 'bar' ;

// ...

return true ;

The doSomething() method of the Example class shown above manipulates a global variable. Other tests are, at least by default, isolated from this modification thanks to PHPUnit's backup-and-restore functionality for global state.

However, you may want to find out which tests execute code that manipulates global state. This is where the new --strict-global-state command-line option (or the respective beStrictAboutChangesToGlobalState configuration setting) comes into play:

$ phpunit --strict-global-state --verbose ExampleTest
PHPUnit 4.6.1 by Sebastian Bergmann and contributors.


Time: 36 ms, Memory: 3.25Mb

There was 1 risky test:

1) ExampleTest::testSomething
--- Global variables before the test
+++ Global variables after the test
@@ @@
     'argc' => 4
+    'foo' => 'bar'

OK, but incomplete, skipped, or risky tests!
Tests: 1, Assertions: 1, Risky: 1.

Please note that using this feature has an impact on your test suite's performance as a snapshot of global state has to be made before and after each test in order to detect changes made to global variabes, super-global variables, or static attributes in user-defined classes during a test's execution.

About the author

Sebastian Bergmann
Sebastian Bergmann
Twitter LinkedIn Xing
Share this article
Driving Change PHPUnit 4.7 and Three Shades of Green