Skip to content

[DX] Simplify command testing #17470

@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

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy