Obtaining output of a symfony command via shell_exec / ApplicationTester etc. in symfony unit test

I’d like to run a command in a separate process from a unit test and obtain its output. I’ve tested several options like using shell_exec or the ApplicationTester-class. While the command is obviously executed (I checked by inserting some side-effects), its output cannot be obtained when executed from the unit test.

However, if I create a small stand-alone php-file (see below, runDummyCmd.php) that contains a corresponding shell_exec, I obtain the output of the symfony command.

How to reproduce

Dummy-Command:

<?php


namespace AppCommand;

use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;

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

Test-Case:

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

Outputs
Output of the unit-test:

"env APP_ENV=test PROJECT_DIR/bin/console app:dummycmd"
null

Output of the execution of runDummyCmd.php on the console:

string(41) "env APP_ENV=test bin/console app:dummycmd"
string(6) "Test!
"

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *