symfony: Cannot test sending email from command with assertEmailCount()

Symfony version(s) affected

5.3.9

Description

I use a command to send an email.

I wrote a PHPUnit test for that with CommandTester as explained here : https://symfony.com/doc/current/console.html#testing-commands

The test fails on the email count.

How to reproduce

  1. Write a command that send an email
  2. Write a test that assert how many emails are sent

Test example :

<?php

namespace CircularX\Common\Tests\Service;

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

class CommandTest extends KernelTestCase
{
    public function testEmail()
    {
        $kernel = static::createKernel();
        $application = new Application($kernel);

        $command = $application->find('app:send-email');
        $container = $application->getKernel()->getContainer();
        $commandTester = new CommandTester($command);
        $commandTester->execute([]);

        // the output of the command in the console
        $output = $commandTester->getDisplay();
        $this->assertEmailCount(1); // will say that no emails are sent 

    }
}

Possible Solution

it seems that there is 2 different MessageEvents object. One when the command is running. Another one when the assertEmailCount is called.

Additional Context

No response

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 17 (14 by maintainers)

Most upvoted comments

replace
$kernel = static::createKernel(); to $kernel = self::bootKernel(); and should work


//        $kernel = static::createKernel();
        $kernel = self::bootKernel();

        $application = new Application($kernel);

        $command = $application->find('app:send-mail');
        $commandTester = new CommandTester($command);
        $commandTester->execute([]);

        $this->assertEmailCount(1);

Hi!

I was able to reproduce the bug. I created a reproduction project here on the 43828_testing_email branch. There are 2 tests:

  • one for the MailService where the assertion is working
  • one for the SendMailCommand where the assertion is not working

Status: Reviewed

Thanks to everyone involved here in helping each other and to also improve the documentation. 😍 Closing here now then.