【问题标题】:PHPunit mockobject abstract and static methodPHPunit mockobject 抽象和静态方法
【发布时间】:2010-07-14 14:55:13
【问题描述】:

我想测试一个抽象类的方法。在这个类中是否有一个静态的抽象方法。

我使用 PHPUnit。使用普通的抽象方法它可以工作:

<?php
abstract class AbstractClass
{
  public function concreteMethod()
  {
    return $this->abstractMethod();
  }

  public abstract function abstractMethod();
}

class AbstractClassTest extends PHPUnit_Framework_TestCase
{
  public function testConcreteMethod()
  {
    $stub = $this->getMockForAbstractClass('AbstractClass');
    $stub->expects($this->any())
         ->method('abstractMethod')
         ->will($this->returnValue(TRUE));

    $this->assertTrue($stub->concreteMethod());
  }
}
?>

phpunit file.php 有效。

但如果 abstractMethod 是静态的,它会显示:

PHP 致命错误:类 Mock_AbstractClass_6332ae11 包含 1 个抽象方法,因此必须声明为抽象方法或在 /usr/local/apache2/php5.3/lib/php/PHPUnit/Framework/ 中实现其余方法 (AbstractClass::abstractMethod) TestCase.php(1135) : eval()'d 代码在第 33 行

【问题讨论】:

    标签: php static phpunit mocking abstract


    【解决方案1】:

    你不能有抽象的静态方法。它将在 PHP 中生成一条 E_STRICT 消息。

    为你的类实现设计一个替代策略。

    【讨论】:

      【解决方案2】:

      从 PHP 5.3 开始可以有抽象静态方法,这里讨论: Why does PHP 5.2+ disallow abstract static class methods?

      使用 phpunit 3.5beta,以下工作:

      <?php
      
      class AbstractClassTest extends PHPUnit_Framework_TestCase
      {
        public function testConcreteMethod()
        {
          $stub = new myStub;
          $this->assertTrue($stub->concreteMethod());
        }
      }
      
      
      abstract class AbstractClass
      {
        public function concreteMethod()
        {
          return static::abstractMethod();
        }
      
        public static abstract function abstractMethod();
      }
      
      class myStub extends AbstractClass {
          public static function abstractMethod() {
              return true;
          }
      }
      
      ?>
      

      Sebastian 的 PHPUnit 3.5.0beta1 伯格曼。

      .

      请注意,在整个后期静态绑定问题中,您需要使用“static::”而不是“self::”。 http://php.net/manual/en/language.oop5.late-static-bindings.php

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-24
        • 2012-12-03
        • 1970-01-01
        • 1970-01-01
        • 2014-03-19
        • 2011-02-25
        相关资源
        最近更新 更多