CommandTester: testing a Symfony console command

CommandTester runs a Symfony console command in a test, without a terminal, to check its exit code, what it displays and what it changes.

protected function setUp(): void
{
    self::bootKernel();
    $this->commande = new CommandTester((new Application(self::$kernel))->find('app:registre:purger'));
}

public function testLeModeABlancNeSupprimeRien(): void
{
    $this->enregistrer($this->reservation('Boromir', '2026-07-02', 'honoree'));

    $this->assertSame(Command::SUCCESS, $this->commande->execute(['--dry-run' => true]));
    $this->assertSame(['Boromir'], $this->restantes());
    $this->assertStringContainsString('1 booking would be purged', $this->commande->getDisplay());
}

You find the command by its name in the FrameworkBundle Application, built on the test's kernel: it receives its real services. execute() takes arguments and options in an array, ['--avant' => '2026-08-01'], and returns the exit code, which getStatusCode() gives back later; getDisplay() returns everything that was printed, and setInputs() prepares the answers to questions. The trap: only testing the message. A command that announces "25 bookings purged" may have left five in the database. Only a test that reads the database again, with data chosen to cross the edge cases, like an incomplete last batch or a date right on the limit, unmasks it.

The exercises start from Gorm's inventory, driven by CommandTester tests, then have you write the tests of the ledger's big clean-up, which must pass on the command as it is and make four mutants fail; finally, they have you protect the whole storytelling evenings feature, down to the reminder command.

3 exercises work on this concept, by writing code in the browser.

In the tracks

Related concepts

Console command#[Option]Exit codes