How can I test a service in symfony2?
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.
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/project
phpunit -c app src/Caremonk/MainSiteBundle/Tests/Services/GeoTest.php