【问题标题】:how to test a parent call to a class wrapper如何测试对类包装器的父调用
【发布时间】:2017-03-03 14:19:41
【问题描述】:

我想通过一些测试来涵盖以下课程:

namespace Nietonfir\RaygunBundle\Services;

use Raygun4php\RaygunClient;

class Client extends RaygunClient implements NietonfirRaygunClient
{
    private $defaultTags = null;

    protected function mergeTags($tags)
    {
        if (is_array($this->defaultTags)) {
            if (is_array($tags)) {
                $tags = array_merge($this->defaultTags, $tags);
            } else {
                $tags = $this->defaultTags;
            }
        }

        return $tags;
    }

    public function setDefaultTags(array $tags)
    {
        if (0 == count($tags)) {
            $this->defaultTags = null;
        }

        $this->defaultTags = $tags;
    }

    public function setVersion($version)
    {
        parent::SetVersion($version);
    }

    public function sendException($exception, $tags = null, $userCustomData = null, $timestamp = null)
    {
        $tags = $this->mergeTags($tags);
        parent::SendException($exception, $tags, $userCustomData, $timestamp);
    }

    public function sendError($errno, $errstr, $errfile, $errline, $tags = null, $userCustomData = null, $timestamp = null)
    {
        $tags = $this->mergeTags($tags);
        return parent::SendError($errno, $errstr, $errfile, $errline, $tags, $userCustomData, $timestamp);
    }
}

具体来说,我想测试sendException 使用正确的$tags 参数调用parent::SendException。问题当然是以某种方式嘲笑父母,但我认为这几乎是不可能的。我正在考虑重构类,以便通过属性使Client 指向RaygunClient 的实例。这样,它可能是可测试的,但我不确定这是一种很好的方法。毕竟,我想要的是用规范化的参数稍微改变原来的父类调用。

欢迎提出任何建议。

【问题讨论】:

  • " 我想测试 sendException 使用正确的 $tags 参数调用 parent::SendException。" -- 你即将编写一个脆弱的测试。测试方法的效果,而不是它的实现。
  • @axiac 是的,可能是。但是该方法只是调整了一个参数。唯一的parent::SendError 效果是通过curl exec 命令发送错误。我仍在考虑如何正确测试预期的行为
  • 撇开重新设计以组合而不是继承这一点不谈,我认为您的系统肯定会从将所有 curl 内容提取到一个单独的类中受益。您将获得所有相关的东西更可测试和干燥的。你可能会想到做两件事——一个只是对 php curl 函数的包装,另一个被更多地用于满足你的客户端类的特定需求。

标签: php unit-testing phpunit


【解决方案1】:

我将此作为评论,但它可以作为您的答案和可能的解决方案。

您在 cmets 中阐明您希望在测试用例中调用的方法将发送一个 cURL 请求。您希望避免实际上在测试期间发送该请求,因为您正在测试的不是 PHP 的 cURL 库。如果您的 cURL 调用在该方法中,您可能应该将其提取到另一个类。

然后,您将能够在您的测试中模拟 那个 类,将其注入到您尝试测试的 实际 系统中,并断言当该方法调用以发送 cURL 请求,请求中的参数与您在测试用例中所期望的相匹配。对于您的测试如何这些参数显示它们的方式并不重要,但我假设它们在通过您的父类汇集时会以某种可检测('assertable')的方式有所不同'方法。

随后系统会检测到破坏此功能的系统更改(通过向 cURL 请求提供错误参数)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 2014-05-29
    相关资源
    最近更新 更多