简体   繁体   English

如何使用PHPUnit在ZFC RBAC下测试控制器

[英]How do I use PHPUnit to test a Controller under ZFC RBAC

I am pretty new to unit testing and have just started my journey learning how to use tests to make my applications more reliable. 我是单元测试的新手,刚刚开始学习如何使用测试使我的应用程序更可靠的旅程。

I am using Zend Framework 3 and am following this guide https://docs.zendframework.com/tutorials/unit-testing/ 我正在使用Zend Framework 3,并且正在遵循本指南https://docs.zendframework.com/tutorials/unit-testing/

What I want to do is test a route that requires a user to be Authenticated and have the correct ZFR Rbac role. 我想做的是测试一条路由,该路由要求用户经过身份验证并具有正确的ZFR Rbac角色。

   public function testOverviewActionCanBeAccessed()
   {
    //Setup a mock user
    $user = $this->createMock(User::class);
    $user->method('getRoles')->willReturn(['admin']);

    //Setup the mock auth identity interface
    $identity = $this->createMock('Zend\Authentication\AuthenticationService');
    $identity->method('getIdentity')
        ->willReturn($user);


    //Run the following test

    $this->dispatch('/cp/overview');
    $this->assertResponseStatusCode(200);
    $this->assertModuleName('ControlPanel');
    $this->assertControllerName(AgentController::class);
    $this->assertControllerClass('AgentController');
    $this->assertMatchedRouteName('cp/overview');
}

At the moment when I run the test I get the following error: 在运行测试的那一刻,我收到以下错误:

PHPUnit 6.2.4 by Sebastian Bergmann and contributors.

F                                                                   1 / 1 (100%)

Time: 1.27 seconds, Memory: 16.00MB

There was 1 failure:

1) ControlPanelTest\Controller\AgentControllerTest::testOverviewActionCanBeAccessed
Failed asserting response code "200", actual status code is "302"

Exceptions raised:
Exception 'ZfcRbac\Exception\UnauthorizedException' with message 'You are not authorized to access this resource' in /var/www//public_html/application/vendor/zf-commons/zfc-rbac/src/ZfcRbac/Guard/AbstractGuard.php:66

/var/www//public_html/application/vendor/zendframework/zend-test/src/PHPUnit/Controller/AbstractControllerTestCase.php:482
/var/www/public_html/application/module/ControlPanel/test/Controller/AgentControllerTest.php:40

So my question is how do I setup RBAC in the test? 所以我的问题是如何在测试中设置RBAC?

So this is how I have solved this issue. 所以这就是我解决这个问题的方式。

This suggestion helped solve the issue 这个建议帮助解决了这个问题

My working code: 我的工作代码:

<?php
namespace ControlPanelTest\Controller;

use ControlPanel\Controller\ControlPanelController;
use Zend\Stdlib\ArrayUtils;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
use ZfcRbac\Identity\IdentityInterface;
use ZfcRbac\Identity\IdentityProviderInterface;
use ZfcRbac\Service\RoleService;

class AgentControllerTest extends AbstractHttpControllerTestCase
{
    protected $traceError = true;
    protected $guard;

    public function setUp()
    {
        $configOverrides = [];

        $this->setApplicationConfig(ArrayUtils::merge(
        // Grabbing the full application configuration:
            include __DIR__ . '/../../../../config/application.config.php',
            $configOverrides
        ));

        parent::setUp();
    }

    public function rbacGuards($roles)
    {
        /**
         * Deal with Rbac Guards
         */
        $roleService = $this->getApplicationServiceLocator()->get(RoleService::class);
        $identityProvider = $this->prophesize(IdentityProviderInterface::class);
        $identity = $this->prophesize(IdentityInterface::class);
        // Here you use the setter to inject your mocked identity provider
        $roleService->setIdentityProvider($identityProvider->reveal());
        $identityProvider->getIdentity()->shouldBeCalled()->willReturn($identity->reveal());
        $identity->getRoles()->shouldBeCalled()->willReturn($roles);
    }

    public function testModuleActionsCanBeAccessed()
    {
        $this->rbacGuards(['admin']);

        $this->dispatch('/cp/overview');
        $this->assertResponseStatusCode(200);
        $this->assertModuleName('ControlPanel');
        $this->assertControllerName(ControlPanelController::class);
        $this->assertControllerClass('ControlPanelController');
        $this->assertMatchedRouteName('cp/overview');

    }
}

Hope this helps someone running unit tests and needing to set the underlying zfc rbac role. 希望这对运行单元测试并需要设置基础zfc rbac角色的人员有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM