Access Symfony 2 container via Unit test?

Support is now built into Symfony. See http://symfony.com/doc/master/cookbook/testing/doctrine.html

Here’s what you could do:

namespace AppBundle\Tests;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class MyDatabaseTest extends KernelTestCase
{
    private $container;

    public function setUp()
    {
        self::bootKernel();

        $this->container = self::$kernel->getContainer();
    }
}

For a bit more modern and re-usable technique see https://gist.github.com/jakzal/a24467c2e57d835dcb65.

Note that using container in unit tests smells. Generally it means your classes depend on the whole container (whole world) and that is not good. You should rather limit your dependencies and mock them.

Leave a Comment