【问题标题】:phpunit not recognising use of count()phpunit 无法识别 count() 的使用
【发布时间】:2014-11-28 05:40:15
【问题描述】:

我有一个实现内置 Countable 接口的 PHP 对象。然后我模拟这个对象进行单元测试:

    $mapper = $this->getMockBuilder("Search_Model_Mapper_Search")
        ->disableOriginalConstructor()
        ->setMethods(array("find", "count"))
        ->getMock();
    $mapper->expects($this->once())
        ->method("find")
        ->with(array("body" => "kajsgfkblkjasfgdjkb"))
        ->will($this->returnValue($mapper));
    $mapper->expects($this->once())
        ->method("count")
        ->will($this->returnValue(0));

被测试的代码部分如下:

    $results = $this->getMapper("fulltext")->find(array("body" => $requestParams['q']));
    if (count($results) === 0) {
        $this->view->messages[] = "Sorry, no results were found. Please check your search terms and try again";
        return; 
    }

PHPUnit 4.0.17 无法识别 count() 的使用 - 我必须使用 $results->count() 才能满足断言。

PHPUnit 3.4 没有这个问题。

我在 PHPUnit 文档中找不到任何帮助解决此问题的内容 - 有什么我遗漏的吗?

【问题讨论】:

    标签: php interface count mocking phpunit


    【解决方案1】:

    事实证明,我在 PHPUnit 的 Zend 实现中过度依赖自动加载行为,并且对 PHPUnit 的模拟对象的更改感到不满。

    在这种特定情况下,由于 Zend/PHPUnit 和自动加载的限制,被模拟的类没有被自动加载(测试不是引导整个应用程序 - 也不应该,因为这应该是一个单元测试) -这曾经在 PHPUnit 3.4 中导致“找不到类”错误,但新的 PHPUnit 4.x 实现将构造一个存根类。存根类没有实现任何接口,所以 PHP 内置的 count() 不知道对象是 Countable。

    我现在需要被模拟的类的特定源文件,并且模拟(和内置的 PHP count())的行为与我预期的完全一样。

    【讨论】:

      【解决方案2】:

      Count 是 PHP 的内部函数,不会在您的场景中模拟。您嘲笑了对计数的 getMapper() 调用 (getMapper->Count())。对于您的测试,只需模拟 $this->getMapper("fulltext")->find() 并让它不返回任何内容,因此 PHP count() 将等于 0。

      【讨论】:

      • PHP 内置的 count 函数应该调用模拟的 count 方法(就像在 phpunit 3.4 中所做的那样),因为模拟的类正在实现 Countable。
      • 如果您只是在模拟中对所有方法使用“任何”,如果 PHPUnit 及其实现发生结构变化,这是否有帮助?否则不确定。
      猜你喜欢
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 2011-04-18
      • 2020-01-09
      • 2015-11-13
      • 2011-08-19
      • 2017-07-03
      • 1970-01-01
      相关资源
      最近更新 更多