views:

15

answers:

2

Hi,

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  A: 

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

Devise an alternative strategy for your class implementation.

Artefacto
A: 

As of PHP 5.3 is it possible to have abstract static methods, discussed here: http://stackoverflow.com/questions/999066/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

edorian