battis / phpunit-sessions
Extension to PHPUnit to handle PHP sessions more gracefully
Installs: 22
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
pkg:composer/battis/phpunit-sessions
Requires
- phpunit/phpunit: ^10.0
README
Extension to PHPUnit to handle PHP sessions more gracefully
Install
composer require --dev battis/phpunit-sessions
Configure
In phpunit.xml:
<phpunit ... bootstrap="tests/bootstrap.php" > ... <extensions> <extension class="Battis\PHPUnit\Sessions\Extension" /> </extensions> </phpunit>
In tests/bootstrap.php:
require_once __DIR__ . "/../vendor/autoload.php"; Battis\PHPUnit\Sessions\Bootstrap::execute();
How it works
Fundamentally, there are two problems with working with sessions and cookies when testing in PHP:
- PHPUnit runs from the CLI, so
$_COOKIESand$_SESSIONSdon't exist. - PHPUnit starts output before any of the code under test that works with sessions is executed, generating errors about output being sent before headers, etc.
To address this, this extension enables an output buffer as PHPUnit starts, buffering all of the output until after the last test is run. (You lose nothing but the immediacy of the output -- you'll still see it all, but only after a heart-stopping pause.)
In addition, when the script run from the CLI, $_SESSIONS AND $_COOKIES are initialized as empty arrays which can then be manipulated as usual.