【问题标题】:How to teste an action on Zend Framework 2 and ZfcUser with zfcUserIdentity Helper如何使用 zfcUserIdentity Helper 测试 Zend Framework 2 和 ZfcUser 上的操作
【发布时间】:2015-01-10 01:35:09
【问题描述】:

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

我该如何做这个测试?我想模拟这种方法,但我不知道该怎么做。

【问题讨论】:

    标签: zend-framework2 phpunit zfcuser bjyauthorize


    【解决方案1】:

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

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

    【讨论】:

    • 感谢@Danielss89 我无法完全理解如何模拟 ZfcUserIdentity 控制器插件,但我查看了代码并使其模拟 AuthenticationService 并期望 getIdentity 方法上的用户实体。完美运行。
    【解决方案2】:

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

    【讨论】:

    • 我正在使用 ZfcRbac(权限);如果你不是,你不需要getRoles,你会更专注于充实$userMock
    猜你喜欢
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多