How to get the EntityManager inside of webtestcases in Symfony2 How to get the EntityManager inside of webtestcases in Symfony2 symfony symfony

How to get the EntityManager inside of webtestcases in Symfony2


You can retrieve the DIC (Dependency Injection Container) through the Kernel, which is a protected member of the WebTestCase.

You could do this from within your WebTestCase:

$em = $this->kernel->getContainer()->get('doctrine.orm.entity_manager');

Update

From your own comment, there is even a shortcut for this (since you will have a client anyway):

$client = $this->getClient();$container = $client->getContainer();

As is mentioned in the docs.


If you have your client, you can get the Entity Manager from it:

$em = $client->getContainer()->get('doctrine.orm.entity_manager');

Don't use `getEntityManager, it is deprecated since Symfony 2.1.

enjoy :)


Things have changed and I'd like to add an update valid for Symfony 4.

If you need to access services in your tests you still need to get the container first. This can be done like:

$container = self::$container;

Now you can get a service, in this example the entity manager:

$this->em = $container->get('doctrine.orm.entity_manager');

I use $this assuming the statement is written in the setUp method and needed in other test methods.

The relevant section of the official Symfony documentation.