从Symfony 2测试用例运行控制台命令

vin*_*nux 24 php symfony

有没有办法从Symfony 2测试用例运行控制台命令?我想运行doctrine命令来创建和删除模式.

Vit*_*ian 72

文档章节介绍了如何从不同位置运行命令.请注意,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()));
    }
}
Run Code Online (Sandbox Code Playgroud)

方案二

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

PS家伙,别丢人的Symfony2与调用exec()...


Squ*_*zic 5

文件告诉你建议的方式做到这一点.示例代码粘贴在下面:

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 这是用于从另一个命令运行命令,而不是从测试用例运行. (7认同)

Kla*_* S. -2

自我上次回答以来,该文档已更新,以反映调用现有命令的正确 Symfony 2 方式:

http://symfony.com/doc/current/components/console/introduction.html#calling-an-existing-command

  • 这不是真正的 Symfony 方式 (13认同)
  • 这甚至不是一个好方法,因为您无法正确解析输出。您还可能会遇到环境问题(如果 php 不在运行测试的用户路径中怎么办?)。 (6认同)