I am using Symfony with the FOSUserBundle and now I like to test some things like:
- Doctrine lifecycle
- Controller behind firewall
For those tests I need to be a specific user or at least in a user group. How do I mock a user session so that ...
- The lifecycle field like "createdAt" will use the logged in user
- The Controller act like some mocked user is logged in
Example:
class FooTest extends ... {
function setUp() {
$user = $this->getMock('User', ['getId', 'getName']);
$someWhereGlobal->user = $user;
// after this you should be logged in as a mocked user
// all operations should run using this user.
}
}
You can easily do that with LiipFunctionalTestBundle which authorize you lot of shortcut for create Unit Test.
If already you have a form user for create or edit you can use this for your test unit workflow user in your application :
use the makeClient method for logging test
use your form for test your creation
testing "createdAt" with just call findOneBy in repository user like this
You can do this with LiipFunctionalTestBundle. Once you have installed and configured the Bundle, creating and user and log in in tests is easy.
Create a fixture for your user
This creates a user which will be loaded during tests:
If you want to use groups of users, you can see the official documentation.
Log in as this user in your test
As explained in LiipFunctionalTestBundle's documentation, here is how to load the user in the database and log in as this user:
What I would do in this case is to create a
CustomWebTestCase
which extends the SymfonyWebTestCase
. In the class I would create a method which does the authentication for me.Here is an example code:
The code above will directly create a valid user session and will skip the firewall entirely. Therefore you can create whatever
$user
you want and it will still be valid. The important part of the code is located in the methodcreateAuthentication
. This is what does the authentication magic.One more thing worth mentioning - make sure you have set
framework.session.storage_id
tosession.storage.mock_file
in yourconfig_test.yml
so that Symfony will automatically mock sessions instead of you having to deal with that in each test case:Now in your test case you would simply extend
MyWebTestCase
and call thecreateAuthenticatedClient()
method:You can see an example in the Symfony official documentation as well.