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

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

我是单元测试的新手,刚刚开始学习如何使用测试使我的应用程序更可靠的旅程。

我正在使用 Zend Framework 3 并遵循本指南 https://docs.zendframework.com/tutorials/unit-testing/

我想做的是测试一条路由,该路由要求用户经过身份验证并具有正确的 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');
}

在我 运行 测试的那一刻,我得到以下错误:

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

所以我的问题是如何在测试中设置 RBAC?

这就是我解决这个问题的方法。

suggestion 帮助解决了问题

我的工作代码:

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

    }
}

希望这对 运行 单元测试和需要设置底层 zfc rbac 角色的人有所帮助。