Symfony2 gets configuration parameters in unit test

I have a Symfony2 service that is built using a parameter from config.yml using dependency injection. Now I try to execute the unit test and find that the unit test does not have access to the container and therefore to the service. So I had to build one using a data layout. It would be advisable for me if I could now read the configuration parameter (first go to config_test.yml, then config.yml, etc.), but it seems to be impossible. This seems to make unit testing of the service cumbersome, since I will need to encode the initialization parameters in the test instead of the configuration files.

If it is really not possible to build a service with parameters from config.yml during unit test, does anyone know the logic about why this is Bad Thing ™?

+7
source share
4 answers

I found this post because I myself need configuration options in my tests. This was the first hit on Google.

However, this is a solution that works. There may be better ones.

<?php ... require_once(__DIR__ . "/../../../../../app/AppKernel.php"); class MediaImageTest extends WebTestCase { private $_application; private $storagePath; public function setUp() { $kernel = new \AppKernel('test', true); $kernel->boot(); $this->_application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel); $this->_application->setAutoExit(false) $this->storagePath = $this->_application->getKernel()->getContainer()->getParameter('media_path'); } ... } 

You can also look at this: Accessing a Symfony 2 container through Unit test? It is a cleaner solution for accessing the kernel as part of unit tests.

+5
source

This works for me:

 class MyServiceTest extends WebTestCase { public function testCookies() { $client = static::createClient(); $myParams = $client->getKernel()->getContainer()->getParameter('my_params'); } } 
+8
source

Unit testing is testing a class in isolation from other classes. For the unit test of your service you do not need to read anything from the configuration. Just pass the value in your test. In the end, it can potentially work with other values, right?

Of course, if there is any logic / validation around the accepted values, you should probably cover it with tests. Think about how you would do it if you took this value from the configuration. You simply cannot verify the behavior with different values.

If you want to check the correct operation of your application (your classes interact as you expect), use functional tests or an acceptance testing tool (for example, Behat).

+2
source

I am using Symfony 3.2.2, but I think this might work for you too.

This is just a line:

 $export_dir = static::$kernel->getContainer()->getParameter('export_dir'); 
0
source

All Articles