PHP

Mock chain method using Mockery

Hi

i just found the coolest way how to mock some class that have chained method. here the sample.

Our case now, we want to mock isAuthenticated in securityContext (Symfony2)


// some snippet from your class
$securityContext = $this->get('security.context'); //get container security.context
$isAutenticated = $securityContext->getToken()->isAuthenticated();

Using PHPUnit_Framework_TestCase


$token = $this->getMockBuilder('App\FooBundle\Security\Authentication\Token\UserToken')->disableOriginalConstructor()->getMock();
$token->expects($this->any())->method('isAuthenticated')->will($this->returnValue(true));
$securityContext = $this->getMockBuilder('Symfony\Component\Security\Core\SecurityContext')->disableOriginalConstructor()->getMock();
$securityContext->expects($this->any())->method('getToken')->will($this->returnValue($token));
$this->assertTrue($securityContext->getToken()->isAuthenticated());

as you see, you need mock UserToken first, then put it in securityContext.

using mockery

$securityContext = Mockery::mock('Symfony\Component\Security\Core\SecurityContextInterface');
$securityContext->shouldReceive('getToken->isAuthenticated')->andReturn(true);

Just type chain method ‘getToken->isAuthenticate’ then you don’t need mock UserToken class 🙂