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?