作者:sharon_chan的秘密花园 | 来源:互联网 | 2023-02-05 18:39
我有以下PHPUnit测试用例:
$mailer = $this->getMockBuilder(MailerInterface::class)->getMock();
$simpleMailer = new SimpleMailer($mailer);
$message = (new Message())
->setTo($user)
->setFrom($from)
->setSubject($subject)
->setTemplate(SimpleMailer::TEMPLATE)
->setContext(['message' => $body]);
if ($bcc) { $message->addBcc($bcc); }
$mailer
->expects($this->once())
->method('send')
->with($this->equalTo($message));
$simpleMailer->sendMessage($user, $subject, $body, $from, $bcc);
在更改Message类之前,此方法一直工作良好。Message类现在在构造上设置一个唯一的ID,这意味着它equalTo
现在返回false,具有以下区别:
MailerBundle\Document\Message Object (
- 'id' => '5a372f3c-a8a9-4e1e-913f-d756244c8e52'
+ 'id' => '11176427-7d74-4a3c-8708-0026ae666f8b'
'type' => null
'user' => Tests\TestUser Object (...)
'toName' => ''
'toAddress' => null
'domain' => null
'fromName' => null
'fromAddress' => 'user@example.org'
'bccAddresses' => Array (...)
'subject' => 'subject'
'textBody' => null
'htmlBody' => null
'template' => 'MailerBundle:MailTemplates:...l.twig'
'context' => Array (...)
)
有什么方法可以从相等性检查中排除某些属性?
1> Alex Blex..:
如果您的Message
类具有吸气剂,则可以在with
函数中使用回调以仅匹配您关心的属性。类似于
$mailer
->expects($this->once())
->method('send')
->with($this->callback(function(Message $message) use ($user, $from, $subject, $body) {
return $message->getTo() == $user
&& $message->getFrom() == $from
&& $message->getSubject() == $subject
&& $message->getTemplate() == SimpleMailer::TEMPLATE
&& $message->getContext()['message'] == $body
}));