Closed
Description
Problem
Testing commands is unnecessarily complicated. This article explains how to do it:
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Tester\CommandTester;
// ...
public function testExecute()
{
// ...
$commandTester = new CommandTester($command);
$helper = $command->getHelper('question');
$helper->setInputStream($this->getInputStream('Test\\n'));
$commandTester->execute(array('command' => $command->getName()));
$this->assertEquals('/.../', $commandTester->getDisplay());
}
protected function getInputStream($input)
{
$stream = fopen('php://memory', 'r+', false);
fputs($stream, $input);
rewind($stream);
return $stream;
}
Solution
Testing a command should be simple: tell me the command's name, give me the input that the user would type in and test the output. Could we translate this idea to code?
use Symfony\Component\Console\Tester\CommandTester;
// ...
public function testExecute()
{
// ...
$command = new CommandTester('app:my-command');
$command->setInputs(array('yes', 'Acme', 'yes'));
$command->execute();
$this->assertEquals('...', $command->getDisplay());
}
The ->setInputs()
method defines what the user would type in. Symfony adds a trailing \n
to each input.
Thoughts, comments, better ideas? Thanks!