Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 getting config params in unit test

I have a Symfony2 service that is constructed using a parameter from config.yml using dependency injection. I'm now trying to unit test it and find that the unit test does not have access to the container and therefore the service. So I should built one myself using mock data. It would make sense to me if I could now read the config parameter (going first to config_test.yml then config.yml etc etc) but it appears that isn't possible either. This appears to make unit testing a service cumbersome as I would need to code the initialisation parameters into the test instead of the config files.

If there really is no way to construct a service with parameters from config.yml during a unit test, does anyone know the logic as to why it is a Bad Thing™?

like image 694
Craig Avatar asked Oct 23 '12 22:10

Craig


2 Answers

This works for me:

class MyServiceTest extends WebTestCase
{
    public function testCookies()
    {
        $client = static::createClient();

        $myParams = $client->getKernel()->getContainer()->getParameter('my_params');
    }
}
like image 132
timhc22 Avatar answered Oct 12 '22 03:10

timhc22


I found this post, because I needed config parameters in my tests myself. This was the first hit on Google.

However, this is a solution which works. There might 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 might look in to this too: Access Symfony 2 container via Unit test? Is a much cleaner solution accessing the kernel within unit tests.

like image 8
fanta Avatar answered Oct 12 '22 04:10

fanta