Symfony 5: How to test that an email was sent by a command in (with Mailer)

  mailer, php, symfony, symfony5, unit-testing

In a Symfony 5 application, I use Mailer to send emails.
I wrote a command wich sends a notification email, and I want to write a unit test to ensure the email has been sent, and then test the content of the headers and body.

So far, here is the test:

<?php

namespace AppTestsCommand;

use SymfonyBundleFrameworkBundleConsoleApplication;
use SymfonyBundleFrameworkBundleTestKernelTestCase;
use SymfonyComponentConsoleTesterCommandTester;

class IngestCommandTest extends KernelTestCase
{
    /** @var string a file that is ingested */
    private $fileOK='path/to/test/file';

    public function testIngestOK()
    {
        $kernel = static::createKernel();
        $application = new Application($kernel);
        // Boot the kernel in order to make the services accessible
        self::bootKernel();

        $command = $application->find('app:ingest');
        $commandTester = new CommandTester($command);
        $commandTester->execute([
            'file' => $this->fileOK,
        ]);

        // Status must be ok (0)
        $status = $commandTester->getStatusCode();
        $this->assertEquals(0, $status);

        // ...other tests

        // Test if mail is sent in the process

        // This test is failing, and all the others too.. 
        $this->assertEmailCount(1);
        $this->assertEmailIsQueued($this->getMailerEvent(0));

        $email = $this->getMailerMessage(0);
        $this->assertEmailHeaderSame($email, 'To', '[email protected]');
        $this->assertEmailTextBodyContains($email, 'It was ok');
    }
}

The first test $this->assertEmailCount(1); is failing, but the mail was clearly sent during the process.

When I var_dump($this->getMailerMessages());, I also got an empty array…

What am I missing? Thanks.

Source: Symfony Questions

One Reply to “Symfony 5: How to test that an email was sent by a command in (with Mailer)”

LEAVE A COMMENT