Additional I wish add info about redefine $mailer in functional yii2 codeception tests:
You shouldn't define the _beforeSuite inside your Cest classes. Instead, you should use the Helper class inside _support.
/**
* Set \Codeception\Module\Yii2::$mailer to \Yii::$app->mailer from test
* For example
* public function _before(FunctionalTester $I)
* {
* \Yii::$app->set('mailer', \frontend\fixtures\MockMailer::class);
* $I->configureMailer();
* $I->amOnPage(['site/contact']);
* }
*/
public function configureMailer()
{
/** @var \Codeception\Module\Yii2 $module */
$module = $this->getModule('Yii2');
/** @var \yii\base\Application $app */
$app = $module->app;
/** @var \Codeception\Lib\Connector\Yii2 $connector */
$connector = $module->client;
$connector::$mailer = $app->get('mailer');
}
class ContactFailCest
{
public function _before(FunctionalTester $I)
{
\Yii::$app->set('mailer', \frontend\fixtures\MockMailer::class);
$I->configureMailer();
$I->amOnPage(['site/contact']);
}
public function checkContactSubmitCorrectDataSendFail(FunctionalTester $I)
{
$I->submitForm('#contact-form', [
'ContactForm[name]' => 'tester',
'ContactForm[email]' => '[email protected]',
'ContactForm[subject]' => 'test subject',
'ContactForm[body]' => 'test content',
'ContactForm[verifyCode]' => 'testme',
]);
$I->dontSeeEmailIsSent();
$I->see(Yii::t('main', 'There was an error sending your message.'));
}
}
namespace frontend\fixtures;
class MockMailer extends \Codeception\Lib\Connector\Yii2\TestMailer
{
protected function sendMessage($message)
{
return false;
}
}