You are browsing the Symfony 4 documentation, which changes significantly from Symfony 3.x. If your app doesn't use Symfony 4 yet, browse the Symfony 3.4 documentation.
Testing with Sessions
Testing with Sessions¶
Symfony is designed from the ground up with code-testability in mind. In order to test your code which utilizes sessions, we provide two separate mock storage mechanisms for both unit testing and functional testing.
Testing code using real sessions is tricky because PHP's workflow state is global and it is not possible to have multiple concurrent sessions in the same PHP process.
The mock storage engines simulate the PHP session workflow without actually starting one allowing you to test your code without complications. You may also run multiple instances in the same PHP process.
The mock storage drivers do not read or write the system globals
session_name(). Methods are provided to simulate this if
getId(): Gets the session ID.
setId(): Sets the session ID.
getName(): Gets the session name.
setName(): Sets the session name.
For unit testing where it is not necessary to persist the session, you should
swap out the default storage engine with
use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; $session = new Session(new MockArraySessionStorage());
For functional testing where you may need to persist session data across
separate PHP processes, change the storage engine to
use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage; $session = new Session(new MockFileSessionStorage());
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.