有没有办法从Symfony 2测试用例运行控制台命令?我想运行doctrine命令来创建和删除模式。
答案 0 :(得分:72)
这个documentation chapter解释了如何从不同的地方运行命令。请注意,使用exec()
满足您的需求是非常糟糕的解决方案......
在Symfony2中执行控制台命令的正确方法如下:
use Symfony\Bundle\FrameworkBundle\Console\Application as App;
use Symfony\Component\Console\Tester\CommandTester;
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 Symfony\Component\Console\Input\StringInput;
use Symfony\Bundle\FrameworkBundle\Console\Application;
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。伙计们,不要在调用exec()
...
答案 1 :(得分:5)
docs告诉您建议的方法。示例代码粘贴在下面:
protected function execute(InputInterface $input, OutputInterface $output)
{
$command = $this->getApplication()->find('demo:greet');
$arguments = array(
'command' => 'demo:greet',
'name' => 'Fabien',
'--yell' => true,
);
$input = new ArrayInput($arguments);
$returnCode = $command->run($input, $output);
// ...
}
答案 2 :(得分:-1)
是的,如果你的目录结构是
/symfony
/app
/src
然后你会跑
phpunit -c app/phpunit.xml.dist
从单元测试中,您可以使用
运行php命令passthru("php app/console [...]") (http://php.net/manual/en/function.passthru.php)
exec("php app/console [...]") (http://www.php.net/manual/en/function.exec.php)
或将命令放在后面的刻度
php app/consode [...]
如果从symofny以外的目录运行单元测试,则必须调整app目录的相对路径才能使用。
从应用程序运行它:
// the document root should be the web folder
$root = $_SERVER['DOCUMENT_ROOT'];
passthru("php $root/../app/console [...]");
答案 3 :(得分:-3)
自我上一次回答以来,文档已经更新,以反映调用现有命令的正确Symfony 2方式:
http://symfony.com/doc/current/components/console/introduction.html#calling-an-existing-command