0

Following this way Unit Testing a Zend Framework 2 application I am work with ZfcUser and try to test some action in my controller. But when the test is executed I get and error because I am using $this->zfcUserIdentity() to get the user name in my view.

How to can I make this test? I think to mock this method, but I don't have idea how to do that.

2 Answers2

0

You can take a look at the ZfcUser tests: https://github.com/ZF-Commons/ZfcUser/blob/master/tests/ZfcUserTest/Controller/UserControllerTest.php#L61-L279

Basicly you have to mock the ZfcUserIdentity controller plugin and tell the controller plugin manager to use that mock.

Danielss89
  • 863
  • 1
  • 11
  • 17
  • Thanks @Danielss89 I can't understand perfectly how to mock the ZfcUserIdentity controller plugin but I looked the code and make it mocking the AuthenticationService and expect the user entity on getIdentity method. Work perfectly. – William Espindola Nov 18 '14 at 18:23
0

I use something like this in my AbstractHttpControllerTestCase:

/**
 * @param array $roles  e.g. ['admin']
 */
protected function login($roles) {
    $userMock = $this->getMock('Application\Entity\User', [], [], '', false);
    $userMock->expects($this->any())
    ->method('getRoles')->will($this->returnValue($roles));

    $storageMock = $this->getMock('\Zend\Authentication\Storage\NonPersistent');
    $storageMock->expects($this->any())
    ->method('isEmpty')->will($this->returnValue(false));
    $storageMock->expects($this->any())
    ->method('read')->will($this->returnValue($userMock));

    $sm = $this->getApplicationServiceLocator();
    $auth = $sm->get('Zend\Authentication\AuthenticationService');
    $auth->setStorage($storageMock);
}

Then in my test itself:

$this->login(['admin']);
$this->dispatch($url);
Derek Illchuk
  • 5,638
  • 1
  • 29
  • 29
  • I'm using ZfcRbac (permissions); if you're not you don't need that `getRoles` and you'd focus more on fleshing out the `$userMock`. – Derek Illchuk Mar 24 '15 at 01:08