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

184 views Asked by At

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/

What I want to do is test a route that requires a user to be Authenticated and have the correct ZFR Rbac role.

   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?

1

There are 1 answers

1
HappyCoder On BEST ANSWER

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.