I am writing unit test for an existing code which is like this
class someClass {
public function __construct() { ... }
public function someFoo($var) {
...
$var = "something";
...
$model = new someClass();
model->someOtherFoo($var);
}
public someOtherFoo($var){
// some code which has to be mocked
}
}
Here how should I be able to mock the call to function “someOtherFoo” such that it doesn’t execute “some code” inside someOtherFoo?
class someClassTest {
public function someFoo() {
$fixture = $this->getMock('someClass ', array('someOtherFoo'));
$var = "something";
....
// How to mock the call to someOtherFoo() here
}
}
Is it possible to mock out the constructor so that it returns my own constructed function or variable?
Thanks
Wherever you have
new XXX(...)in a method under test, you are doomed. Extract the instantiation to a new method–createSomeClass(...)–of the same class. This allows you to create a partial mock of the class under test that returns a stubbed or mock value from the new method.In the test, mock
createSomeClass()in the instance on which you callsomeFoo(), and mocksomeOtherFoo()in the instance that you return from the first mocked call.Keep in mind that because the instance is creating another instance of the same class, two instances will normally be involved. You could use the same mock instance here if it makes it clearer.