我试图为我正在使用的电子邮件抽象类编写PHPUnit测试。该类与Mailgun API进行交互,但我不想在我的测试中触摸这个,我只想返回我对Mailgun所期望的响应。
在我的测试中,我有一个设置方法:
class EmailTest extends PHPUnit_Framework_TestCase
{
private $emailService;
public function setUp()
{
$mailgun = $this->getMockBuilder('SlmMail\Service\MailgunService')
->disableOriginalConstructor()
->getMock();
$mailgun->method('send')
->willReturn('<2342423@sandbox54533434.mailgun.org>');
$this->emailService = new Email($mailgun);
parent::setUp();
}
public function testEmailServiceCanSend()
{
$output = $this->emailService->send("me@test.com");
var_dump($output);
}
}
这是电子邮件类的基本概要
use Zend\Http\Exception\RuntimeException as ZendRuntimeException;
use Zend\Mail\Message;
use SlmMail\Service\MailgunService;
class Email
{
public function __construct($service = MailgunService::class){
$config = ['domain' => $this->domain, 'key' => $this->key];
$this->service = new $service($config['domain'], $config['key']);
}
public function send($to){
$message = new Message;
$message->setTo($to);
$message->setSubject("test subject");
$message->setFrom($this->fromAddress);
$message->setBody("test content");
try {
$result = $this->service->send($message);
return $result;
} catch(ZendRuntimeException $e) {
/**
* HTTP exception - (probably) triggered by network connectivity issue with Mailgun
*/
$error = $e->getMessage();
}
}
}
var_dump($output);
目前正在输出NULL
而不是我期待的字符串。方法send
我在模拟对象中的存根通过参数具有依赖性,当我直接调用$mailgun->send()
时,它会基于此错误,所以我想知道这是否是失败的背后场景。有没有办法传递这个论点,或者我应该以不同的方式处理它?</ p>
答案 0 :(得分:1)
奇怪的是,它不会在Email::__construct
中抛出异常。
预期参数是字符串,MailgunService
对象在电子邮件构造函数中实例化。在你的测试中,你传递的是对象,所以我希望和行
$this->service = new $service($config['domain'], $config['key']);
您需要的是:
class Email
{
public function __construct($service = null){
$config = ['domain' => $this->domain, 'key' => $this->key];
$this->service = $service?: new MailgunService($config['domain'], $config['key']);
}
此外,捕获异常并在Email::send
中不返回任何内容可能不是一个好主意。