Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Symfony 2 container via Unit test?

How do I access the Symfony 2 container within a Unit test? My libraries need it so it's essential.

The test classes extend \PHPUnit_Framework_TestCase so there is no container.

like image 742
Tower Avatar asked Jan 23 '12 13:01

Tower


2 Answers

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.

like image 143
Jakub Zalas Avatar answered Sep 19 '22 05:09

Jakub Zalas


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,); } 
like image 28
Babou34090 Avatar answered Sep 23 '22 05:09

Babou34090