如何使用zfcUserIdentity Helper在Zend Framework 2和ZfcUser上测试操作

时间:2014-11-13 01:33:43

标签: zend-framework2 phpunit zfcuser bjyauthorize

遵循这种方式Unit Testing a Zend Framework 2 application我正在使用ZfcUser并尝试在我的控制器中测试一些操作。但是当测试执行时,我得到并且错误,因为我使用$this->zfcUserIdentity()来获取我的视图中的用户名。

如何进行此测试?我想嘲笑这种方法,但我不知道如何做到这一点。

2 个答案:

答案 0 :(得分:0)

您可以查看ZfcUser测试:https://github.com/ZF-Commons/ZfcUser/blob/master/tests/ZfcUserTest/Controller/UserControllerTest.php#L61-L279

基本上你必须模拟ZfcUserIdentity控制器插件并告诉控制器插件管理器使用该模拟。

答案 1 :(得分:0)

我在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);
}

然后在我的测试中:

$this->login(['admin']);
$this->dispatch($url);