Is there a way to run a console command from a Symfony 2 test case? I want to run the doctrine commands for creating and dropping schemas.
See Question&Answers more detail:osIs there a way to run a console command from a Symfony 2 test case? I want to run the doctrine commands for creating and dropping schemas.
See Question&Answers more detail:osThis documentation chapter explains how to run commands from different places. Mind, that using exec()
for your needs is quite dirty solution...
The right way of executing console command in Symfony2 is as below:
use SymfonyBundleFrameworkBundleConsoleApplication as App;
use SymfonyComponentConsoleTesterCommandTester;
class YourTest extends WebTestCase
{
public function setUp()
{
$kernel = $this->createKernel();
$kernel->boot();
$application = new App($kernel);
$application->add(new YourCommand());
$command = $application->find('your:command:name');
$commandTester = new CommandTester($command);
$commandTester->execute(array('command' => $command->getName()));
}
}
use SymfonyComponentConsoleInputStringInput;
use SymfonyBundleFrameworkBundleConsoleApplication;
class YourClass extends WebTestCase
{
protected static $application;
public function setUp()
{
self::runCommand('your:command:name');
// you can also specify an environment:
// self::runCommand('your:command:name --env=test');
}
protected static function runCommand($command)
{
$command = sprintf('%s --quiet', $command);
return self::getApplication()->run(new StringInput($command));
}
protected static function getApplication()
{
if (null === self::$application) {
$client = static::createClient();
self::$application = new Application($client->getKernel());
self::$application->setAutoExit(false);
}
return self::$application;
}
}
P.S. Guys, don't shame Symfony2 with calling exec()
...