How to teste an action on Zend Framework 2 and ZfcUser with zfcUserIdentity Helper

329 views Asked by At

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

There are 2 answers

1
Danielss89 On BEST ANSWER

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.

1
Derek Illchuk On

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);