【问题标题】:Dependency on mock method with PHPUnit使用 PHPUnit 对 mock 方法的依赖
【发布时间】: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-&gt;send() 时,它会基于此出错,所以我想知道这是否是幕后失败的原因。有没有办法传递这个论点,或者我应该以不同的方式处理这个问题?

【问题讨论】:

  • 您可能需要包含Email::send 的代码,因为问题似乎出在此处。测试看起来还可以。如果Email::send 是像return $this-&gt;mailgun-&gt;send(); 这样的简单代理,您的$output 应该包含预设响应。
  • 将基本电子邮件类添加到问题中

标签: php unit-testing testing phpunit


【解决方案1】:

奇怪的是它没有在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']);
    }

此外,在Email::send 中捕获异常并不返回任何内容可能不是一个好主意。

【讨论】:

  • 好地方!是的,我不确定为什么这还没有引发错误。 email::send 中的异常处理只是一个 sn-p 顺便说一句,它被处理了。
猜你喜欢
  • 1970-01-01
  • 2015-04-04
  • 2017-01-28
  • 2016-01-05
  • 1970-01-01
  • 2015-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多