In PHPUnit, how do I mock parent methods?

Viewed 28638

I want to test a class method that calls upon a parent method with the same name. Is there a way to do this?

class Parent {

    function foo() {
        echo 'bar';
    }
}

class Child {

    function foo() {
            $foo = parent::foo();
            return $foo;
    }
}

class ChildTest extend PHPUnit_TestCase {

    function testFoo() {
        $mock = $this->getMock('Child', array('foo'));

        //how do i mock parent methods and simulate responses?
    }
}
5 Answers

Here is how I did it, I have no idea if this is correct but it works:

class parentClass {
    public function whatever() {
        $this->doSomething();
    }
}

class childClass extends parentClass {
    public $variable;
    public function subjectUnderTest() {
        $this->variable = 'whocares';
        parent::whatever();
    }
}

now in the test i do:

public function testSubjectUnderTest() {
    $ChildClass = $this->getMock('childClass', array('doSomething'))
    $ChildClass->expects($this->once())
               ->method('doSomething');
    $ChildClass->subjectUnderTest();
    $this->assertEquals('whocares', $ChildClass->variable);
}

what the ?

My reasoning here is that all i really want to test is whether or not my variable got set. i don't really care about what happens in the parent method but since you can't prevent the parent method from being called what i do is mock the dependent methods of the parent method.

now go ahead and tell me i'm wrong :)

Related