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

时间:2017-05-03 10:35:35

标签: cakephp cakephp-3.4

我正在尝试使用get()类提供的posts() / IntegrationTestCase方法为发送电子邮件的操作编写测试。

代码是这样的:

$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

我一直在寻找,但我不明白如何为测试设置传输。

感谢。

1 个答案:

答案 0 :(得分:1)

我没有遇到这样的要求,但以下情况应该有效。

/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'
        ]
    ]
];