Quantcast
Channel: Active questions tagged symfony4 - Stack Overflow
Viewing all articles
Browse latest Browse all 3925

PHPUnit test for method that sends email once

$
0
0

I am trying to write some unit test where I can check if creator of a post should not receive same email twice.

I am new at testing (not new in Symfony.) I tried some basic test and they work.

First of the problem is that this is a method inside of and DataPersister class within Api Platform which is called everytime entity is persisted and it sends an email to a user..

final class EmailDataPersister {   public function persist($data, array $context = [])   {    $result = $this->decorated->persist($data, $context);    if (        $data instanceof User&& (            ($context['collection_operation_name'] ?? null) === 'post')    ) {        $this->sendEmail($data);    }    return $result;}    private function sendEmail(User $user)    {        $email = (new EmailNotification())            ->setTitle('Hello ' . $user->getName())            ->setFrom('sender@sent.com')            ->setAddress($user->getEmail)            ->setBody('This is a new email');        $this->messageBus->dispatch($email);    } }

Tried something like:

class someModelTest extends TestCase

  public function testEmails(){    $this->satEmail('test@pmg.co');    $this->assertMessageCount(1, 'should have sent one email');    $msg = $this->getMessages()[0];    $this->assertArrayHasKey('test@pmg.co', $msg->getTo());}public function satEmail($email){    $msg = (new \Swift_Message('Testing..'))        ->setSubject('Hello')        ->setBody('Hello')        ->setFrom('helle@example.com')        ->setTo($email);    $this->mailer->send($msg);}

I think I need to add..

        $model = $this->getMock('someModel', array('setFrom', 'setTo', 'setSubject', 'send'));        $controller->expects($this->once())            ->method('setFrom');        $controller->expects($this->once())            ->method('setTo');        $controller->expects($this->once())            ->method('setSubject');        $controller->expects($this->once())            ->method('send');        $model->sendEmail();    }

I can not figure out should I call that method inside the class or what should I define model controller etc?


Viewing all articles
Browse latest Browse all 3925

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>