2016-08-02 13 views
0

電子メールを送信するphpunitとcakephp 3.xのシェルでテストケースを作ってみたい。私は、これはシェルから電子メールをテストするCakephp 3.x

/** 
* 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(); 
} 

を機能しかし、これは動作しません持っている私のテストクラスで

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); 
      } 

     /* ... */ 
    } 
} 

:これは私のシェルに機能です。 アイデアメールが正常に送信されたかどうか、何回送信されたかを確認したい。

答えて

1

あなたのコードを書いた方法はうまくいかないでしょう。

$email = new Email('staff'); 

そして:あなたはクラスを使用すると、魔法のようにあなたのモックオブジェクトを$電子メール変数を置き換えるために呼び出しを期待するにはどうすればよい

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

?コードをリファクタリングする必要があります。

これは、私はそれを行うだろうかです:SubscriptionMailerよう

まずimplement a custom mailer。あなたのメールコードをこのメーラークラスに入れてください。そうすれば分離して再利用可能なコードを作成することができます。

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

あなたのテストでは、あなたのシェルのgetMailer()メソッドをモックし、あなたの電子メールモックを返す。

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

あなたはすでに期待していることができます。からのデータを処理しているモデルオブジェクト(テーブル)の

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

また、あなたのシェル方法が何をしているかに応じて、多分(カスタムメーラークラスを使用して再度)afterSaveコールバックに電子メールを送信することをお勧めしますあなたのシェル。例at the end of this pageを確認してください。

関連する問題