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.
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,); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With