Reputation: 1081
I have a contact controller which render my contact form and validate the request. After validation success the contact controller create a Contactobject and call the method proceedContact from ContactHandler. Now i would like to write a phpunit test for my handler. It's my first unit test. I have following questions.
Exists an similar example for this use case?
namespace AppBundle\Utils;
use AppBundle\Entity\Contact;
class ContactHandler
{
private $mailer;
private $templating;
private $translator;
private $emailTo;
private $emailCc;
public function __construct($mailer, $templating, $translator, $emailTo, $emailCc)
{
$this->mailer = $mailer;
$this->templating = $templating;
$this->translator = $translator;
$this->emailTo = $emailTo;
$this->emailCc = $emailCc;
}
public function proceedContact(Contact $contact)
{
$subject_part_1 = $this->translator->trans('contact_mail_subject');
$subject_part_2 = $this->translator->trans($contact->getRequest());
$subject = $subject_part_1 . ' - ' . $subject_part_2;
$message = \Swift_Message::newInstance()
->setSubject($subject)
->setFrom($contact->getEmail())
->setTo($this->emailTo)
->setCc($this->emailCc)
->setBody(
$this->templating->render(
'Emails/contact.html.twig',
array('name' => $contact->getName(), 'message' => $contact->getMessage())
),
'text/html'
);
$this->mailer->send($message);
}
}
Upvotes: 0
Views: 73
Reputation: 13167
This kind of logic (email sending) should not be done in an Entity.
You should create a service instead, or create a method in the corresponding controller.
Also, when the architecture of your logic is ok, to deal with the service container in your tests, see the corresponding part of the documentation.
See also this very good article about using Dependency Injection in tests.
And, to send e-mail from your tests (more functional than unit in this case), see E-mail testing.
Try to use this informations to build your test, and if you encounter difficulties, ask a precise question for a precise problem here.
Upvotes: 1