Scott Joudry
Scott Joudry

Reputation: 902

PHPUnit test and abstract class with a method named 'Method'

I am in the process of testing an abstract class that has a method called Method.

Here is my abstract class (abridged):

abstract class ClassToTest {

  function Method($_value = NULL) {
    // based on the value passed in a different value is returned.
  }
}

Here is my PHPUnit class:

class ClassToTestTest extends PHPUnit_Framework_TestCase {
  public $object = NULL;

  public function setUp() {
    $this->object = $this->getMockForAbstractClass('ClassToTest');
  }

  public function testMethod() {

    // passing no value should return NULL
    $this->assertNull($this->object->Method());

    // passing a value should return a value
    $this->assertEquals($this->object->Method($method), 'return_value');
  }
}

Based on PHPUnit Documentation I should be able to use

$stub->expects($this->any())->method('Method')->willReturn('foo');

somehow, but I cannot figure out how to make this work.

How can I use PHPUnit to test a method called Method?

Also, I don't have the option to rename the method to something else.

Upvotes: 2

Views: 1649

Answers (1)

Jakub Zalas
Jakub Zalas

Reputation: 36191

Class you're testing is surely the only class you shouldn't be mocking. You wouldn't be really testing it if you faked its method calls.

Since your class is abstract you need to test it through a concrete implementation. If you don't have one, create it for the test.

class MyClassToTest extends ClassToTest
{
    // implement abstract methods
}
class ClassToTestTest extends PHPUnit_Framework_TestCase
{
    private $object;

    protected function setUp()
    {
        $this->object = new MyClassToTest();
    }

    public function testMethod()
    {
        $this->assertSame('return_value', $this->object->Method('foo'));
    }

}

Upvotes: 3

Related Questions