【问题标题】:Testing email from shell Cakephp 3.x从 shell Cakephp 3.x 测试电子邮件
【发布时间】:2016-12-07 19:56:50
【问题描述】:

我想用 phpunit 和 cakephp 3.x 制作测试用例,shell 发送电子邮件。这是我在 shell 中的功能:

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('dario@example.com')
                  ->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();
}

但这不起作用。 有任何想法吗?我想检查邮件是否成功发送以及发送了多少次。

【问题讨论】:

    标签: shell cakephp phpunit cakephp-3.0


    【解决方案1】:

    你编写代码的方式行不通。

    $email = new Email('staff');
    

    还有:

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

    您如何期望您调用的类神奇地将 $email 变量替换为您的模拟对象?你需要重构你的代码。

    我会这样做:

    首先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 方法正在做什么,也许最好在处理来自您的 shell 数据的模型对象(表)的 afterSave 回调(再次使用自定义邮件程序类)中发送电子邮件。检查示例at the end of this page

    【讨论】:

      猜你喜欢
      • 2011-07-30
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      • 2015-12-21
      • 2011-05-26
      • 2011-09-18
      • 2014-06-15
      相关资源
      最近更新 更多