2016-08-02 35 views
0

我想用phpunit和cakephp 3.x來製作測試用例,發送郵件的shell。這是我的功能分爲殼:從Shell CakePHP 3.x測試電子郵件

class CompaniesShellTest extends TestCase 
{ 
    public function monthlySubscription() 
    { 
     /* .... */ 

      $email = new Email('staff'); 
      try { 

       $email->template('Companies.alert_renew_success', 'base') 
        ->theme('Backend') 
        ->emailFormat('html') 
        ->profile(['ElasticMail' => ['channel' => ['alert_renew_success']]]) 
        ->to($user->username) 
        //->to('[email protected]') 
        ->subject('Eseguito rinnovo mensile abbonamento') 
        ->viewVars(['company' => $company, 'user' => $user]) 
        ->send(); 
      } catch (Exception $e) { 
       debug($e); 
      } 

     /* ... */ 
    } 
} 

在我的測試類我有這個功能

/** 
* setUp method 
* 
* @return void 
*/ 
public function setUp() 
{ 
    parent::setUp(); 
    $this->io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock(); 
    $this->CompaniesShell = new CompaniesShell($this->io); 
} 
/** 
* tearDown method 
* 
* @return void 
*/ 
public function tearDown() 
{ 
    unset($this->CompaniesShell); 
    parent::tearDown(); 
} 
/** 
* Test monthlySubscription method 
* 
* @return void 
*/ 
public function testMonthlySubscription() 
{ 
    $email = $this->getMock('Cake\Mailer\Email', array('subject', 'from', 'to', 'send')); 

    $email->expects($this->exactly(3))->method('send')->will($this->returnValue(true)); 

    $this->CompaniesShell->MonthlySubscription(); 
} 

但是,這是行不通的。 任何想法?我想檢查郵件是否成功發送以及發送多少次。

回答

1

您編寫代碼的方式不起作用。

$email = new Email('staff'); 

和:

$email = $this->getMock('Cake\Mailer\Email', array('subject', 'from', 'to', 'send')); 

你怎麼能指望你叫奇蹟般地與你的模擬對象替換$電子郵件變量的類?你需要重構你的代碼。

這是我會怎麼做:

首先implement a custom mailer像SubscriptionMailer。把你的郵件代碼放到這個郵件類中。這確保你有很好的分離和可重用的代碼。

public function getMailer() { 
    return new SubscriptionMailer(); 
} 

在你的測試模擬你的shell的getMailer()方法並返回你的電子郵件模擬。

$mockShell->expects($this->any()) 
    ->method('getMailer') 
    ->will($this->returnValue($mailerMock)); 

然後,你可以做你已經有的期望。

$email->expects($this->exactly(3))->method('send')->will($this->returnValue(true)); 

還取決於你的shell方法是幹什麼的,也許這是更好地寄於afterSave回調的電子郵件(再次使用自定義郵件類)的模型對象(表)是從處理數據的你的外殼。檢查示例at the end of this page