OiO.lk Blog PHP How to unit test a symfony/console application command?
PHP

How to unit test a symfony/console application command?


I use only the symfony/console@7.1 library to create a small cli application.

I want to unit test the command as is, yet the the unit test provides no output.

This is my unit test setup:

class TimrOverviewCommandTest extends TestCase
{
    public function testTimrOverviewCommand()
    {
        $input = new ArgvInput(argv: [
            "overview",
            "--csv",
            "tests/csv/day_report.csv"
        ]);

        $buffered = new BufferedOutput();

        $app = new Timr(__DIR__);
        $exitCode = $app->run($input, $buffered);
        $result = $buffered->fetch();

        $this::assertSame(actual: $result, expected: "2024-10-18: Expected 5 / Delivered 5.25\n");
    }
}

This is how my app is setup:

class Timr
{
    private readonly Application $app;

    public function __construct(string $rootDir)
    {
        $parser = new CsvParser($rootDir);

        $app = new Application('timr', '1.0.0');

        $app->add(new TimrReportCommand($parser));
        $app->add(new TimrOverviewCommand($parser));

        $this->app = $app;
    }

    public function run(?InputInterface $input = null, ?OutputInterface $output = null): int
    {
        return $this->app->run($input, $output);
    }
}

There were a couple of related questions, yet most of them seem to be in scope of an entire symfony web application and/or are outdated:



You need to sign in to view this answers

Exit mobile version