Access Symfony 2 container via Unit test? Access Symfony 2 container via Unit test? symfony symfony

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.


You can use this , in your set up function

protected $client;protected $em;/** * PHP UNIT SETUP FOR MEMORY USAGE * @SuppressWarnings(PHPMD.UnusedLocalVariable) crawler set instance for test. */public function setUp(){    $this->client = static::createClient(array(            'environment' => 'test',    ),        array(            'HTTP_HOST' => 'host.tst',            'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0',    ));    static::$kernel = static::createKernel();    static::$kernel->boot();    $this->em = static::$kernel->getContainer()                               ->get('doctrine')                               ->getManager();    $crawler = $this->client->followRedirects();}

Don't forget to set your teardown function

    protected function tearDown(){    $this->em->close();    unset($this->client, $this->em,);}


Update 2018: Since Symfony 3.4/4.0 there is a problem with service testing.

It's called "testing private services", possible solutions are described here


For various different configs you also use lastzero/test-tools package.

It sets up a container for you and is ready to use:

use TestTools\TestCase\UnitTestCase;class FooTest extends UnitTestCase{    protected $foo;    public function setUp()    {        $this->foo = $this->get('foo');    }    public function testBar()    {        $result = $this->foo->bar('Pi', 2);        $this->assertEquals(3.14, $result);    }}