Asserting email was sent with mailhog dsn

465 views Asked by At

Testing my email sending logic, doesn't catch the sent email to mailhog.

// Both ways don't work
$this->assertEmailCount(1, 'smtp://mailhog:1025');
$this->assertEmailCount(1);

Errors I got for both:

Failed asserting that the Transport smtp://mailhog:1025 has sent "1" emails (0 sent).

Failed asserting that the Transport has sent "1" emails (0 sent).

Email is sent. I see it in mailhog. Everytime I run the tests.

private function getMailer(array $mailConfig): MailerInterface
{
    $dsn = match (strtolower($mailConfig['transport'])) {
        'sendgrid' => 'smtp://mailhog:1025',
        'mailchimp' => 'smtp://mailhog:1025',
        default => 'smtp://mailhog:1025'
    };

    $transport = Transport::fromDsn($dsn);

    return new Mailer($transport);
}

Posting the sending functionality as well but think it doesn't matter when email is sent. Is there something specific when testing with mailhog?

1

There are 1 answers

0
ypaquereau On

I got the same problem, and I just add

//...
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Mailer\Mailer;

public function __construct(
        //...
        private readonly EventDispatcherInterface $eventDispatcher
) {
}

public function getMailer(): Mailer
{
    //...
    $transport = Transport::fromDsn($dsn, $this->eventDispatcher);
    return new Mailer($transport);
}

You can also disable delivery in your tests https://symfony.com/doc/current/mailer.html#disabling-delivery