Last Updated: March 02, 2016
·
3.321K
· ohvitorino

Testing Container Aware Commands in Symfony2

If your command is extending Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand, you also need to use Symfony\Bundle\FrameworkBundle\Console\Application to test the command instead of the base Symfony\Component\Console\Application.

Your test class should also extend Symfony\Bundle\FrameworkBundle\Test\WebTestCase and initialize a kernel in order to get usable context within your command.

Example:

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use VLIZ\ToolboxBundle\Command\DownloadCommand;

class DownloadCommandTest extends WebTestCase
{
    /**
     * @inheritDoc
     */
    protected function setUp()
    {
        static::$kernel = static::createKernel();
        static::$kernel->boot();
    }

    public function testDownload()
    {
        $application = new Application(static::$kernel);
        $application->add(new DownloadCommand());

        $command = $application->find('demo:greet');
        $command->setApplication($application);
        $commandTester = new CommandTester($command);
        $commandTester->execute(
                array(
                    'command'      => $command->getName(),
                    'name'         => 'Fabien',
                    '--iterations' => 5,
        );

        $this->assertRegExp('/Fabien/', $commandTester->getDisplay());
    }
}