依赖于 PHPUnit 的模拟方法

Dependency on mock method with PHPUnit

我正在尝试为我正在使用的电子邮件抽象编写 PHPUnit 测试 class。 class 与 Mailgun API 交互,但我不想在测试中触及它,我只想 return 我希望从 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);
    }
}

这是邮件的基本大纲class

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::__construct中抛出异常。 预期参数是 字符串 ,并且 MailgunService 对象在电子邮件构造函数中实例化。在您的测试中,您正在传递 object,所以我希望在第

行出现错误
$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']);
    }

此外,捕获异常并且 return 在 Email::send 中什么都没有可能不是一个好主意。