In PHPUnit, how do I mock parent methods?
You dont mock or stub methods in the Subject-under-Test (SUT). If you feel you have the need to mock or stub a method in the parent of the SUT, it likely means you shouldnt have used inheritance, but aggregation.
You mock dependencies of the Subject-under-Test. That means any other objects the SUT requires to do work.
An approach that works to my is the implementation of a wrap to the parent call on the child class, and finally mock those wrap.
You code modified:
class Parent { function foo() { echo 'bar'; }}class Child { function foo() { $foo = $this->parentFooCall(); return $foo; } function parentFooCall() { return parent::foo(); }}class ChildTest extend PHPUnit_TestCase { function testFoo() { $mock = $this->getMock('Child', array('foo', 'parentFooCall')); //how do i mock parent methods and simulate responses? } }
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 :)