2

In https://symfony.com/doc/current/console.html#testing-commands Users can see how to test Commands using Unit Testing.

The issue is that following this process, Console output made via Monolog can't be tested.

$output = $commandTester->getDisplay();
# Returns ''

Therefore all asserts on the $output are false.

Anybody has any idea on how to unit test Monolog Outputs in Symfony Commands in Symfony 4?

aneth101
  • 509
  • 5
  • 9
  • Does this answer your question? [How to assert a line is logged using Monolog inside Symfony2](https://stackoverflow.com/questions/30664606/how-to-assert-a-line-is-logged-using-monolog-inside-symfony2) – Aerendir Sep 26 '20 at 09:31

1 Answers1

2

I've managed to test Monolog output by adding a TestHandler in monolog "config/packages/test/monolog.yaml"

monolog:
    handlers:
        test:
            type: test
            level: debug

Here is the code in my TestClass

class MyClassCommandTest extends KernelTestCase
{
    /**
     * First validation tests all invalid options
     */
    public function testMyCommand()
    {
        $kernel = static::createKernel();
        $application = new Application($kernel);

        $command = $application->find('my:command:name');
        $commandTester = new CommandTester($command);

        $options['command'] = $command->getName();
        $commandTester->execute([
            'option_name' => 'value'
        ], [
            'verbosity' => OutputInterface::VERBOSITY_VERY_VERBOSE
        ]);

        //I injected the logger inside my command and added a function getLogger to access it
        $logger = $command->getLogger();
        $handlers = $logger->getHandlers();

        $logs = null
        foreach ($handlers as $handler) {
            if ($handler instanceof TestHandler) {
                $logs = $handler;
            }
        }

        $this->assertTrue($logs->hasRecordThatContains('ERROR_STRING_1', Logger::ERROR), 'Missing Error');
        $this->assertTrue($logs->hasRecordThatContains('CRITICAL_STRING_1', Logger::CRITICAL), 'Missing Critical Error');
        $this->assertFalse($logs->hasRecordThatContains('SUCCESS_STRING_1', Logger::INFO), 'Has Success Message');
    }
}

Anyone have any other suggestions on how to validate the output?

aneth101
  • 509
  • 5
  • 9