问题描述
我想在与单元测试不同的过程中运行命令并获取其输出。我已经测试了多个选项,例如使用shell_exec
或ApplicationTester
类。虽然显然已执行了该命令(我通过插入一些副作用进行了检查),但从单元测试中执行时却无法获得其输出。
但是,如果我创建了一个包含相应runDummyCmd.PHP
的小型独立PHP文件(请参见下文shell_exec
),则会获得symfony命令的输出。
如何复制
虚拟命令:
<?PHP
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DummyCommand extends Command
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('app:dummycmd')
->setDescription('Can be used for testing commands')
->setHelp('Does a simple output.');
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input,OutputInterface $output)
{
$output->writeln('Test!');
return 0;
}
}
测试案例:
class MyTest extends MyKernelTestCase
{
protected $projectDir;
protected function setUp(): void
{
parent::setUp();
$this->projectDir = static::$container->getParameter('kernel.project_dir');
}
public function testGetoutputOfCommand() {
$cmd = 'env APP_ENV=test '. $this->projectDir . '/bin/console app:dummycmd';
dump($cmd);
$output = shell_exec($cmd);
dump($output);
}
}
runDummyCmd.PHP:
<?PHP
$cmd = 'env APP_ENV=test bin/console app:dummycmd';
var_dump($cmd);
$output = shell_exec($cmd);
var_dump($output);
?>
"env APP_ENV=test PROJECT_DIR/bin/console app:dummycmd"
null
string(41) "env APP_ENV=test bin/console app:dummycmd"
string(6) "Test!
"
解决方法
您是否尝试过CommandTester类?
$command = $application->find('app:dummycmd');
$commandTester = new CommandTester($command);
$commandTester->execute([
'command' => $command->getName()
]);
$output = $commandTester->getDisplay();