PHPunit mockobject abstract and static method

纵然是瞬间 提交于 2019-12-11 04:37:12

问题


I would like to test a method from an abstract class. In this class is there a abstract method with is static.

I use PHPUnit. With normal abstract methods it works:

<?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 works.

But if the abstractMethod is static it displays:

PHP Fatal error: Class Mock_AbstractClass_6332ae11 contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (AbstractClass::abstractMethod) in /usr/local/apache2/php5.3/lib/php/PHPUnit/Framework/TestCase.php(1135) : eval()'d code on line 33


回答1:


You can't have abstract static methods. It will generate an E_STRICT message in PHP.

Devise an alternative strategy for your class implementation.




回答2:


As of PHP 5.3 is it possible to have abstract static methods, discussed here: Why does PHP 5.2+ disallow abstract static class methods?

With phpunit 3.5beta the following works:

<?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;
    }
}

?>

PHPUnit 3.5.0beta1 by Sebastian Bergmann.

.

Note that you need to use "static::" not "self::" as of the whole late static binding issue. http://php.net/manual/en/language.oop5.late-static-bindings.php



来源:https://stackoverflow.com/questions/3247408/phpunit-mockobject-abstract-and-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!