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?
So this is how I have solved this issue.
This suggestion helped solve the issue
My working code:
Hope this helps someone running unit tests and needing to set the underlying zfc rbac role.