Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

php - Running console command from a Symfony 2 test case

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:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This 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:

Option one

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

Option two

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...