2013-06-24 97 views
7

我試圖在功能測試,測試電子郵件...如何在功能測試測試電子郵件(Symfony2的)

我的源代碼是一樣的example of the cookbook

控制器:

public function sendEmailAction($name) 
{ 
    $message = \Swift_Message::newInstance() 
     ->setSubject('Hello Email') 
     ->setFrom('[email protected]') 
     ->setTo('[email protected]') 
     ->setBody('You should see me from the profiler!') 
    ; 

    $this->get('mailer')->send($message); 

    return $this->render(...); 
} 

而且測試:

// src/Acme/DemoBundle/Tests/Controller/MailControllerTest.php 
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; 

class MailControllerTest extends WebTestCase 
{ 
    public function testMailIsSentAndContentIsOk() 
    { 
     $client = static::createClient(); 

     // Enable the profiler for the next request (it does nothing if the profiler is not available) 
     $client->enableProfiler(); 

     $crawler = $client->request('POST', '/path/to/above/action'); 

     $mailCollector = $client->getProfile()->getCollector('swiftmailer'); 

     // Check that an e-mail was sent 
     $this->assertEquals(1, $mailCollector->getMessageCount()); 

     $collectedMessages = $mailCollector->getMessages(); 
     $message = $collectedMessages[0]; 

     // Asserting e-mail data 
     $this->assertInstanceOf('Swift_Message', $message); 
     $this->assertEquals('Hello Email', $message->getSubject()); 
     $this->assertEquals('[email protected]', key($message->getFrom())); 
     $this->assertEquals('[email protected]', key($message->getTo())); 
     $this->assertEquals(
      'You should see me from the profiler!', 
      $message->getBody() 
     ); 
    } 
} 

但是我得到這個錯誤:

PHP Fatal error: Call to a member function getCollector() on a non-object

問題來源於此行:

什麼想法?

+2

是我的答案有幫助?如果是的話,請upvote /接受,否則請評論如果缺少或不工作:-) – nifr

+0

我無法檢查的時間...但不用擔心,我保留你的解決方案,並會在下週嘗試;) – Ousmane

回答

7

拋出異常,因爲如果探查器未啓用,getProfile()返回false。見here

public function getProfile() 
{ 
    if (!$this->kernel->getContainer()->has('profiler')) { 
     return false; 
    } 

    return $this->kernel->getContainer()->get('profiler')->loadProfileFromResponse($this->response); 
} 

此外enableProfiler()僅啓用探查,如果它與又名啓用該服務容器註冊。見here

public function enableProfiler() 
{ 
    if ($this->kernel->getContainer()->has('profiler')) { 
     $this->profiler = true; 
    } 
} 

現在您必須確保在測試環境中啓用了分析器。 (通常應該是default setting

config_test.yml

framework: 
    profiler: 
     enabled: true 

您可以添加這樣的事情來測試:

$this->assertEquals($this->kernel->getContainer()->has('profiler'), true); 
+0

嗨@nifr,這對我真的很有幫助。 thnx – kuldipem

+1

讀者注意:如果您想在提交表單後使用分析器,則必須禁用重定向。 '$客戶端 - > followRedirects(假); $客戶端 - > enableProfiler(); $客戶 - >提交($形式);/*使用profiler */if($ profile = $ client-> getProfile()){...}/*打開目標頁面*/$ crawler = $ client-> request('GET',$ client-> getResponse() - >包頭中>的get( '位置'));' –