3

I'm trying to write tests for an action that sends an email, using get() / posts() methods provided by the IntegrationTestCase class.

The code is something like this:

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

Normally this code works.

But by testing, I get this error:

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

I've been looking a bit, but I did not understand how to set up a transport only for tests.

Thanks.

Mirko Pagliai
  • 1,220
  • 1
  • 19
  • 36

1 Answers1

1

I didn’t came across such requirement, but the following should work.

In your /tests/bootstrap.php define a constant, so we can tell if we are in a testing environment:

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

In /config/bootstrap.php check against the constant after the default app config file is loaded:

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

Finally create the config file /config/app_tests.php for testing and overwrite some of the default config values:

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