Symfony2 Command Testing


So in the symfony2 docs it says how to test a command, but never says how to get mock or create a kernel. Here’s the code you that may help you out.

use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Acme\DemoBundle\Command\GreetCommand;

class ListCommandTest extends WebTestCase
{
    public function testExecute()
    {
        $kernel = self::createKernel();
        $kernel->boot();

        $application = new Application($kernel);
        $application->add(new GreetCommand());

        $command = $application->find('demo:greet');
        $commandTester = new CommandTester($command);
        $commandTester->execute(array('command' => $command->getName()));

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

        // ...
    }
}

Take note that we are now extending Symfony\Bundle\FrameworkBundle\Test\WebTestCase and added two lines of code to set the $kernel variable.

References and Resources

  • https://github.com/symfony/FrameworkBundle
  • http://symfony.com/doc/current/cookbook/console/console_command.html#testing-commands