我在swiftmailer
中有两个不同的Yii::$app
个实例,名为mailer
和feedback
。 Codeception只能捕获mailer
组件,因此通过feedback
发送是不可测试的。
好的,我尝试使用以下代码绕过它:
protected function _before()
{
$components = Yii::$app->getComponents();
$components['feedback']['class'] =
\Codeception\Lib\Connector\Yii2\TestMailer::class;
Yii::$app->set('mailer', $components['feedback']);
}
但是消息仍然出现在fileTransportPath
目录中,并且测试仍然失败并显示Failed asserting that an array is not empty
(如果我使用通常的mailer
组件运行测试,则不会发生这种情况。)
有解决方案吗?
答案 0 :(得分:0)
首先,我们必须使用\Codeception\Lib\Connector\Yii2\TestMailer
模拟另一个邮件程序组件:
protected function _before()
{
$components = \Yii::$app->getComponents();
$components['feedback']['class'] =
\Codeception\Lib\Connector\Yii2\TestMailer::class;
\Yii::$app->set('feedback', \Yii::createObject($components['feedback']));
}
然后我们可以测试它:
public function testSendSuccess()
{
//sending
$result = \Yii::$app->feedback->compose()->setTextBody('sometext')->->setSubject('somesubject')->send();
$this->assertTrue($result);
//get sent message from memory
$mailer = $this->tester->grabComponent('feedback');
$messages = $mailer->getSentMessages();
$this->assertNotEmpty($messages, 'emails were sent');
$emailMessage = end($messages);
$this->assertInstanceOf(\yii\mail\MessageInterface::class, $emailMessage);
expect($emailMessage->getTo())->hasKey(\Yii::$app->feedback->messageConfig['to']);
expect($emailMessage->getFrom())->hasKey(\Yii::$app->feedback->messageConfig['from']);
expect($emailMessage->getSubject())->contains('somesubject');
}
这很好用。