Skip to content

Impossible to test sending mail from a command with the MailerAssertionsTrait #38035

@bdelesalle

Description

@bdelesalle

Symfony version(s) affected: 4.4.*

Description

When you want to test the sending of mail from a command, you cannot use the MailerAssertionsTrait since it expects an HTTP request.

private static function getMessageMailerEvents(): MessageEvents
{
    if (!self::getClient()->getRequest()) {
        static::fail('Unable to make email assertions. Did you forget to make an HTTP request?');
    }

    if (!$logger = self::$container->get('mailer.logger_message_listener')) {
        static::fail('A client must have Mailer enabled to make email assertions. Did you forget to require symfony/mailer?');
    }

    return $logger->getEvents();
}

How to reproduce

<?php

namespace App\Tests;

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

class MyCommandTest extends WebTestCase
{
    use MailerAssertionsTrait;

    public function testCommand(): void
    {
        $application = new Application(self::$kernel);
        $command = $application->find('app:my-command');
        $commandTester = new CommandTester($command);

        $commandTester->execute(['command' => $command->getName()]);

        self::assertEmailCount(1);
    }
}

Possible Solution

Remove the HTTP request check.

private static function getMessageMailerEvents(): MessageEvents
{
    if (!$logger = self::$container->get('mailer.logger_message_listener')) {
        static::fail('A client must have Mailer enabled to make email assertions. Did you forget to require symfony/mailer?');
    }

    return $logger->getEvents();
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions