A great way to mock chained calls in PHPUnit Few days ago i had to write a groovy test for a java class and i had a long chain of calls to mock. I was not sure how to test it nicely and i started wondering is there a nicer way to do it in PHP. Usually in PHP there is a nice way to do almost anything :D
Chained calls example
So if you have something like:
$this->someService
->getSomething()
->getSomethingElse()
->doMore($x)
->proceed()
->toGetTheFinalCall($y);
If you want to mock it in traditional way you would end up in creating separate mocks for every single call! Which will grow easily to a half of screen of of code just to mock one line! But wait there is a way!
Mocking chained calls
$value = 'some mocked value';
$mock = $this->getMock('ServiceClass', array('getSomething',
'getSomethingElse','doMore','proceed','toGetTheFinalCall' ), array(), '', false);
$mock->expects($this->any())->method('toGetTheFinalCall')
->will($this->returnValue($value));
$mock->expects($this->any())->method($this->anything())
->will($this->returnValue($mock));
This way every consecutive call to the mock returns itself so it can be chained as many times as you want. You wont check if methods are called in the desired order but that is not really a problem. Ultimately what you want is to test the code that does something with the results of the call.
Main Blog Categories
About the author

Hi, my name is Artur Ejsmont,
welcome to my blog.
I am a passionate software engineer living in Sydney and working for Yahoo! Drop me a line or leave a comment.
Enjoy!
Comments
Post new comment