I want to mock a method with PHPunit in Zend Framework 2.
The method is part of a 'AbstractController' class which is extended by the class I am testing.
The code I use to test:
public function testAddPostAction()
{
$this->mockBjy();
$this->mockZFC();
$zfcUser = $this->getMockBuilder('Common\Controller\AbstractController')->getMock();
$zfcUser ->method('getUserId')
->will($this->returnValue('2'));
$this->assertEquals(2, $zfcUser->getUserId());
$this->dispatch('/leaverequest/add','POST', array('user' => '2','reasonforleave' => 'PHPunit','leaveRequestDates'=> '05/06/2015 - 05/15/2015'));
$this->assertModuleName('Employment');
$this->assertControllerName('employment\controller\leaverequest');
$this->assertControllerClass('LeaveRequestController');
$this->assertActionName('add');
$this->assertMatchedRouteName('leaverequest/add');
}
The code in the abstract Controller:
protected function getUserId()
{
return $this->zfcUserAuthentication()
->getIdentity()
->getId();
}
The code in the controller being tested that requires this method, look at the 2nd parameter in the method being called on the second line of the if statement ($this->getUserId()).
public function addAction()
{
if ($this->getRequest()->isPost()) {
$this->getServiceLocator()->get('leaveRequestService')->addLeaveRequest($this->getRequest()->getPost()->toArray(), $this->getUserId());
$returnValue = $this->redirect()->toRoute('leaverequest/list');
} else {
$users = $this->getServiceLocator()->get('userService')->findAllUsers();
$returnValue = new ViewModel(array('users' => $users));
}
return $returnValue;
}
I would need the mock the result of this method, but am unable to do so with the current code. The message I receive is as follows: Call to a member function getId() on a non-object in .....
Thank you in advance :)
So I have realised that mocking the abstract was a bad approach and should rather mock the leave request service called by the dispatch method. I have now tried to mock the leave request addLeaveRequestService, but the second parameter $this->getUserId is still being triggered causing the unit test to go the the getId method in the abstract controller where it fails and provides the error message " "call to member function on a non-object"