8000 [DX] Simplify command testing · Issue #17470 · symfony/symfony · GitHub
[go: up one dir, main page]

8000
Skip to content
[DX] Simplify command testing #17470
Closed
Closed
@javiereguiluz

Description

@javiereguiluz

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    ConsoleDXDX = Developer eXperience (anything that improves the experience of using Symfony)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0