Yii2 + Codeception:如何测试通过另一个邮件程序组件发送邮件?

时间:2018-05-06 22:57:39

标签: yii2 codeception

我在swiftmailer中有两个不同的Yii::$app个实例,名为mailerfeedback。 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组件运行测试,则不会发生这种情况。)

有解决方案吗?

1 个答案:

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

这很好用。