PHPUnit mocks with callbacks

PHPUnit mocks are really easy and usefull. With them you're able to change the behaviour and return values of which ever class you want to test.

$awesomeUrl = "http://blog.liplex.de";
/** @var UniqueHelper|\PHPUnit_Framework_MockObject_MockObject $uniqueHelper */
$uniqueHelper = $this->getMockObject(
    'Liplex\Helper\UniqueHelper',
    [
        'getAwesomeUrl' => [
            'call' => 'once',
            'return' => $awesomeUrl
        ]
    ]
);

You can also replace services with mock services on the fly:

class AweseomeControllerTest extends WebTestCase
{
    public function testCalculationWithAwesomeThingAction()
    {
    	$client = $this->createClient();
        $customResult = 55;
        
		/** @var AwesomeService|\PHPUnit_Framework_MockObject_MockObject $awesomeService */
		$awesomeService = $this->getMockObject(
    		'Liplex\Service\AwesomeService',
    		[
        		'calculateWithAwesomeThing' => [
            		'call' => 'once',
            		'return' => $customResult
        		]
    		]
		);
		$client->getContainer()->set('liplex.awesome', $awesomeService);
        
        $client->request('POST', '/calculation/');
    }
}

And with return callbacks you're even able to adapt parameter of function calls right before you execute them:

/** @var AwesomeService|\PHPUnit_Framework_MockObject_MockObject $awesomeService */
$awesomeService = $this->getMock(
    'Liplex\Service\AwesomeService',
    array(
        'getAwesomeThing',
        'calculateWithAwesomeThing'
    )
);

$awesomeService->expects($this->once())
    ->method('calculateWithAwesomeThing')
    ->will($this->returnCallback(function(AwesomeThing $awesomeThing) {
        $awesomeThing->setStatus(AwesomeThing::STATUS_NICE);
        return $awesomeThing;
    })
);