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();

        $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