我对单元测试还很陌生,并且刚刚开始学习如何使用测试使我的应用程序更可靠的旅程。
我正在使用 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?