我想寫一個功能測試,檢查電子郵件發送與否。我sendemail方法是在服務中定義的,所以我不能夠按照所給出的例子cookbookSymfony3電子郵件服務功能測試
設置 - 控制器有一個形式,當表單提交和有效的,它會調用sendmail的方法,在服務
控制器
public function sampleAction(Request $request){
$sampleEntity = new SampleEntity();
$form = $this->createForm(sampleType::class, $sampleEntity)
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()){
...
$sampleservice = $this->get('sampleservice');
$sampleservice->sendMail();
return $this->render('sample/formsubmitted.html.twig');
}
}
服務
public function sendMail(){
$body = $this->renderTemplate();
$message = \Swift_Message::newInstance()
->setSubject('Sample Mail')
->setFrom($this->sender_mail)
->setTo($this->admin_mail)
->setBody($body);
$this->mailer->send($message);
}
測試
public function testEmailSend(){
$client = static::createClient();
$client->enableProfiler();
$crawler = $client->request('POST', '/sampleform');
$client->followRedirects(false);
$form = $crawler->selectButton('Submit Form')->form();
$crawler = $client->submit($form);
$mailCollector = $client->getProfile()->getCollector('swiftmailer');
$this->assertEquals(1, $mailCollector->getMessageCount());
}
可以把這個信號來解釋更好$crawler = $client->request('POST', '/sampleform');
,在菜譜它說路徑sendmail的行動,但因爲它不是在我的情況下采取行動,寫什麼那裏或我必須採取全新的方法嗎?
除此之外,我嘗試直接從服務調用sendmail,assertEqual給我0,因爲sendmail不訪問(我猜)。關於何處以及如何進行的任何想法。這是我第一次嘗試寫功能測試,所以如果我犯了一些明顯的錯誤,請原諒我。
編輯1
SampleType
public function buildForm(FormBuilderInterface $builder, array $options){
$builder
->add('name', TextType::class, array('data' => 'Sample'))
->add('phone', TextType::class, array('data' => '1234567890'))
->add('save', SubmitType::class, array('label' => 'Submit Form'))
->getForm();
}
編輯2 當試圖直接調用服務,是否有其他方法可以直接調用服務?
public function testEmailSend(){
$client = static::createClient();
$client->enableProfiler();
$crawler = $client->request('POST', '/src/AppBundle/Service/SampleService/sendMail()');
$mailCollector = $client->getProfile()->getCollector('swiftmailer');
$this->assertEquals(1, $mailCollector->getMessageCount());
}
這一個返回「失敗斷言0匹配預期1」。
郵件獲取應用程序成功發送,但要確保在測試以及
確定測試進入'如果($形式 - > isSubmitted()...'行動,因爲你沒有張貼值?你的表單類型是什麼樣子的? – COil
雅,我在'if()'爲true時寫了測試,我已經爲true和false寫了測試,所以試圖擴展sendmail的真正測試。讓我們假設表單中的所有值都有預定義的數據。 –
只需致電您的電子郵件服務即可使用獲取操作。它在開發模式下工作嗎? – COil