【发布时间】:2016-03-21 12:07:13
【问题描述】:
我正在尝试为我正在使用的电子邮件抽象类编写 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() 时,它会基于此出错,所以我想知道这是否是幕后失败的原因。有没有办法传递这个论点,或者我应该以不同的方式处理这个问题?
【问题讨论】:
-
您可能需要包含
Email::send的代码,因为问题似乎出在此处。测试看起来还可以。如果Email::send是像return $this->mailgun->send();这样的简单代理,您的$output应该包含预设响应。 -
将基本电子邮件类添加到问题中
标签: php unit-testing testing phpunit