CakePHP 3.4:仅为测试设置电子邮件传输

CakePHP 3.4: set up an email transport only for tests

我正在尝试使用 IntegrationTestCase class.[=15 提供的 get() / posts() 方法为发送电子邮件的操作编写测试=]

代码是这样的:

$this->getMailer('User')
    ->set('someVarName', 'someVarValue)
    ->send('forgotPassword', [$user]);  

通常此代码有效。

但是通过测试,我得到了这个错误:

1) MeCms\Test\TestCase\Controller\UsersControllerTest::testForgotPassword
BadMethodCallException: Cannot send email, transport was not defined. Did you call transport() or define  a transport in the set profile?

/home/mirko/Libs/Plugins/MeCms/vendor/cakephp/cakephp/src/Mailer/Email.php:2049
/home/mirko/Libs/Plugins/MeCms/vendor/cakephp/cakephp/src/Mailer/Mailer.php:252
/home/mirko/Libs/Plugins/MeCms/src/Controller/UsersController.php:213
/home/mirko/Libs/Plugins/MeCms/vendor/cakephp/cakephp/src/Controller/Controller.php:440
/home/mirko/Libs/Plugins/MeCms/vendor/cakephp/cakephp/src/Http/ActionDispatcher.php:119
/home/mirko/Libs/Plugins/MeCms/vendor/cakephp/cakephp/src/Http/ActionDispatcher.php:93
/home/mirko/Libs/Plugins/MeCms/vendor/cakephp/cakephp/src/Routing/Dispatcher.php:60
/home/mirko/Libs/Plugins/MeCms/vendor/cakephp/cakephp/src/TestSuite/LegacyRequestDispatcher.php:61
/home/mirko/Libs/Plugins/MeCms/vendor/cakephp/cakephp/src/TestSuite/IntegrationTestCase.php:426
/home/mirko/Libs/Plugins/MeCms/vendor/cakephp/cakephp/src/TestSuite/IntegrationTestCase.php:360
/home/mirko/Libs/Plugins/MeCms/tests/TestCase/Controller/UsersControllerTest.php:345

我看了一些,但我不明白如何设置一个仅用于测试的传输。

谢谢。

我没有遇到过这样的要求,但下面应该可以。

在你的/tests/bootstrap.php中定义一个常量,这样我们就可以判断我们是否处于测试环境中:

define('_TEST', true);
// important: define above requiring the /config/bootstrap.php
require dirname(__DIR__) . '/config/bootstrap.php';

/config/bootstrap.php 中检查加载默认 app 配置文件后的常量:

Configure::load('app', 'default', false);

// load an additional config file `/config/app_testing.php` in testing environment
if (defined('_TEST') && _TEST === true) {
    Configure::load('app_tests');
}

最后创建配置文件/config/app_tests.php用于测试并覆盖一些默认配置值:

<?php
return [
    'Email' => [
        'default' => [
            'transport' => 'gmail',
            'log' => true
        ]
    ],
    'EmailTransport' => [
        'gmail' => [
            'host' => 'ssl://smtp.gmail.com',
            'port' => 465,
            'username' => 'GoogleMailUserName',
            'password' => 'GoogleMailPassword',
            'className' => 'Smtp'
        ]
    ]
];