How can I test a service in symfony2?
In your test case, you're not going to get anything in your constructor - you can set up the object you want to test in a setupBeforeClass or setup method, e.g.
public static function setUpBeforeClass(){ //start the symfony kernel $kernel = static::createKernel(); $kernel->boot(); //get the DI container self::$container = $kernel->getContainer(); //now we can instantiate our service (if you want a fresh one for //each test method, do this in setUp() instead self::$geo = self::$container->get('geo');}
(Note also you don't need to set up your test classes as services either, so you can remove your geo_test service from services.yml)
Once you've done that, you should be able to run your test case with something like
cd /root/of/projectphpunit -c app src/Caremonk/MainSiteBundle/Tests/Services/GeoTest.php
If your are not going to test controllers (with client, because controller called like this will use a new container) your test class should just extend KernelTestCase (Symfony\Bundle\FrameworkBundle\Test). To boot the kernel & get services you can do sth like this in your test setup:
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;class MyTest extends KernelTestCase{ public function setUp() { $kernel = self::bootKernel(); $this->geo = $kernel->getContainer()->get('geo'); } ...}
More info:http://symfony.com/doc/current/testing/doctrine.html
Notes:
- To have fresh kernel & services for each test I recommend to use the
setUp
method instead ofsetUpBeforeClass
(like in the accepted answer). - The kernel is always accessible via
static::$kernel
(after booting). - Also works in symfony 3 & 4.
If you do not want to make tests in an application but in a standalone bundle, I would suggest you to take a look at the very detailed answer of this question.