I'm writing a PHPUnit test, where I need to mock some dependency, but I need a couple of methods for it still work as before. I.e., I have:
class Dependency {
// some stuff not important for the test
public function thisOneINeed() {
/// complex code
}
// some more stuff
}
So I was doing something like this:
// prepare mock object
$dep = $this->getMockBuilder('Dependency')->disableOriginalConstructor()->getMock();
// mock out some other method that should return fixed value
$dep->expects($this->any())->method("shouldGetTrue")->will($this->returnValue(true));
// run test code, it will use thisOneINeed() and shouldGetTrue()
$result = $testSubject->runSomeCode($dep);
$this->assertEquals($expected, $result);
And everything is fine except method thisOneINeed()
is mocked out so I don't get the complex code to run and I need it to run for runSomeCode()
to work properly. That code in thisOneINeed()
doesn't call any other methods, but it is needed for the proper test and it doesn't return fixed value, so I can't just put static returnValue() there. And AFAIK PHPunit does not have a method like returnValue()
that says "call parent". It has returnCallback()
but there's no way to tell it "call this method for parent class" as far as I could see.
I could make the list of all methods in Dependency
, remove thisOneINeed
from it and pass it to setMethods()
when constructing the mock, but I don't like that approach, looks kludgy.
I could also do this:
class MockDependency extends Dependency
{
// do not let the mock kill thisOneINeed function
final public function thisOneINeed()
{
return parent::thisOneINeed();
}
}
and then use MockDependency
to build the mock object, and this works too, but I don't like having to do the mock manually.
So is there a better way to do this?