Skip to content

[Console] Adding an example of command test using the ApplicationTester class #19896

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 5.4
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion console.rst
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,46 @@ call ``setAutoExit(false)`` on it to get the command result in ``CommandTester``
You can also test a whole console application by using
:class:`Symfony\\Component\\Console\\Tester\\ApplicationTester`.

Here an example of a test using this class::

use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\ApplicationTester;
use Symfony\Component\Console\Tester\CommandTester;

class WelcomeCommandTest extends KernelTestCase
{
public function testPerson(): void
{
self::bootKernel();
$application = new Application(self::$kernel);
$application->setAutoExit(false);

$applicationTester = new ApplicationTester($application);

$input = [
// Pass the command name
'command' => 'app:welcome-person',

// Pass the different arguments
'firstName' => 'Michael',
'lastName' => 'Jackson',
'hobbies' => ['singing', 'dancing']
];

// Call run to launch the application
$applicationTester->run($input);

$applicationTester->assertCommandIsSuccessful();

$output = $applicationTester->getDisplay();

// Here $output value is "The person is Michael Jackson and his hobbies are the following singing and dancing."
$this->assertStringContainsString('Michael Jackson', $output);
$this->assertStringContainsString('singing and dancing', $output);
}
}

.. caution::

When testing commands using the ``CommandTester`` class, console events are
Expand All @@ -566,7 +606,7 @@ call ``setAutoExit(false)`` on it to get the command result in ``CommandTester``
When testing commands using the :class:`Symfony\\Component\\Console\\Tester\\ApplicationTester`
class, don't forget to disable the auto exit flag::

$application = new Application();
$application = new Application(self::$kernel);
$application->setAutoExit(false);

$tester = new ApplicationTester($application);
Expand Down
Loading