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
- Write a command that send an email
- 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)
replace
$kernel = static::createKernel(); to $kernel = self::bootKernel(); and should work
Hi!
I was able to reproduce the bug. I created a reproduction project here on the
43828_testing_email
branch. There are 2 tests:MailService
where the assertion is workingSendMailCommand
where the assertion is not workingStatus: Reviewed
Thanks to everyone involved here in helping each other and to also improve the documentation. 😍 Closing here now then.