我在测试发送通知电子邮件的Symfony服务时遇到了麻烦。
在我的NotificationService中,我有一个函数将通知持久存储到数据库中,并使用简单的MailHelper类发送通知电子邮件:
public function saveNewNotificationUser($newnotificationuser){
// Get necessary repositories
$doctrine = $this->getDoctrine();
$repo_user = $doctrine->getRepository('AppBundle:User');
$em = $doctrine->getManager();
$notificationuser = $this->getNotificationUserById($newnotificationuser['idnotificationuser']);
$user = $repo_user->findOneByIduser($newnotificationuser['iduser']);
$notification = $this->getNotificationById($newnotificationuser['idnotification']);
if ($notification && $user){
// Persist on database
$notificationuser->setDate(new \DateTime("now"));
$notificationuser->setRead(0);
$notificationuser->setUseruser($user);
$notificationuser->setVariables($newnotificationuser['variables']);
$notificationuser->setNotificationnotification($notification);
$em->persist($notificationuser);
$em->flush();
// Send notification email
// Generate notification structure
$not = $this->createNotificationStructure($newnotificationuser['idnotification'],$newnotificationuser['variables']);
// Define user's dafault language and send notification email
$languagecode = $user->getLanguagelanguage()->getCode();
$mailTo = $user->getEmail();
// Get notification next on user's default language
$text = $not["languages"][$languagecode]["language"];
$this->get('mailHelper')->sendMail("notification",$mailTo,array('body' => $text["description"]), $text["title"]);
return $notificationuser->getIdnotificationUser();
}else{
return false;
}
}
当我测试该功能时,数据库插入正确完成但电子邮件永远不会发送。这是我的测试类:
private $container;
private $em;
public function setUp()
{
self::bootKernel();
$this->container = self::$kernel->getContainer();
$this->em = $this->container->get('doctrine')
->getManager();
}
public function testSaveNewNotificationUser()
{
$notificationService = $this->container->get('notificationService');
$newnotificationuser = array(
'idnotificationuser' => '99',
'iduser' => '69',
'idnotification' => '1',
'variables' => '32;12'
);
$id = $notificationService->saveNewNotificationUser($newnotificationuser);
$item = $this->em
->getRepository('AppBundle:NotificationUser')
->findByIdnotificationUser($id);
$this->assertCount(1, $item);
}
protected function tearDown()
{
parent::tearDown();
$this->em->close();
}
public function testNotificationAction()
{
$client = static::createClient();
$crawler = $client->request('GET', '/api/login/testnotif');
$mailCollector = $client->getProfile()->getCollector('swiftmailer');
// Check that an email was sent
$this->assertEquals(1, $mailCollector->getMessageCount());
$this->assertTrue($client->getResponse()->isSuccessful());
}
但是,如果我在Controller Action中调用SaveNewNotificationUser,使用与testSaveNewNotificationUser中使用的相同的“假”数据,则会发送电子邮件(当disable_delivery设置为false时),我可以通过mailCollector捕获它。
我错过了什么吗?我采取了错误的方法来构建测试吗?