且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在CakePHP中的单元测试期间使用不同的电子邮件配置

更新时间:2023-01-18 21:09:08

最简单的方法是在测试时可能切换到DebugTransport。测试的一部分是,你需要设计你的程序是可测试的。事实上,这里有一些功能和整个蛋糕设计来做到这一点。对于您的应用程序,假设您在用户注册时发送电子邮件:

The easiest way is to probably switch to the DebugTransport while testing. Part of testing is that you need to design your program to be testable. In fact, there are a few functions here and there throughout Cake designed to do just that. For your app, let's assume you send an email when a user registers:

App::uses('CakeEmail', 'Network/Email');
App::uses('AppController', 'Controller');

class UsersController extends AppController {

  public function register() {
    //registration logic
    $email = new CakeEmail();
    $email->from(array('site@example.com' => 'Site'));
    $email->to('you@example.com');
    $email->subject('Registered');
    $email->send('Thanks for registering!');
  }

}

这看起来无害,但你不能mock CakeEmail ,因为它不允许依赖注入,这是测试时必需的。相反, CakeEmail 类应该以允许我们以后更改的方式实例化。例如:

This looks harmless, but you cannot mock CakeEmail because it does not allow for dependency injection, which is necessary when testing. Instead, the CakeEmail class should be instantiated in a way that allows us to change it later. For example:

App::uses('CakeEmail', 'Network/Email');
App::uses('AppController', 'Controller');

class UsersController extends AppController {

  public function register() {
    //registration logic
    $email = $this->_getEmailer();
    $email->from(array('site@example.com' => 'Site'));
    $email->to('you@example.com');
    $email->subject('Registered');
    $email->send('Thanks for registering!');
  }

  public function _getEmailer() {
    return new CakeEmail();
  }

}

因为我们添加了一个辅助函数,我们现在可以测试它(通过嘲笑助手函数)。

Because we added a little helper function, we can now test it (by mocking the helper function).

App::uses('CakeEmail', 'Network/Email');
App::uses('UsersController', 'Controller');

class UsersControllerTest extends ControllerTestCase {

  public function testRegister() {
    $controller = $this->generate('Users', array(
      'methods' => array(
        '_getEmailer'
      )
    ));
    $emailer = new CakeEmail();
    $emailer->transport('Debug');
    $controller
      ->expects($this->any())
      ->method('_getEmailer')
      ->will($this->returnValue($emailer));
  }

}

此测试创建一个mock对象当调用 _getEmailer 方法时,我们的控制器并告诉它返回我们新创建的 $ emailer 由于 $ emailer 已将传输设置为调试,因此可以安全地进行测试。

This test creates a mock object for our controller and tells it to return our newly created $emailer object when the _getEmailer method is called. Since $emailer has set the transport to 'Debug', it's safe for testing.

我们决定该方法返回什么电子邮件对象,嘲笑 CakeEmail 对象,并期望某些返回变得微不足道。

Of course, since now we're deciding what email object the method returns, mocking the CakeEmail object and expecting certain returns becomes trivial.