use*_*259 3 phpunit acl phpspec symfony
我想检查具有访问控制的方法,例如,只授予具有特定角色的方法.因此,我在Symfony中了解两种方式:
当谈到单元测试时(对于我的案例phpspec,但我认为phpunit行为在这种情况下几乎相同),我想测试只有匿名用户应该能够调用方法.数字2,它工作正常.在这里我的设置:
RegistrationHandlerSpec:
class RegistrationHandlerSpec extends ObjectBehavior
{
function let(Container $container, AuthorizationCheckerInterface $auth) {
$container->get('security.authorization_checker')->willReturn($auth);
$this->setContainer($container);
}
function it_should_block_authenticated_users(AuthorizationCheckerInterface $auth)
{
$auth->isGranted("ROLE_USER")->willReturn(true);
$this->shouldThrow('Symfony\Component\Security\Core\Exception\AccessDeniedException')->during('process', array());
}
}
Run Code Online (Sandbox Code Playgroud)
在RegistrationHandler中,我有以下方法:
class RegistrationHandler
{
public function process()
{
$authorizationChecker = $this->get('security.authorization_checker');
if ($authorizationChecker->isGranted('ROLE_USER')) {
throw new AccessDeniedException();
}
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,这种方法工作正常 - 但通常情况下,我更喜欢使用1.带安全性注释(Sensio FrameworkExtraBundle),因此,它不起作用/我不知道为什么当它被编写为注释时没有触发异常:
/**
* @Security("!has_role('ROLE_USER')")
*/
public function process()
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
有没有人知道如何使用@Security注释的第一种方法使这个例子工作,这是更可读和symfony推荐的最佳做法?
在这两种情况下,您都在测试由第三方代码(Symfony框架)提供的行为.遵循规则不要模拟你不拥有的东西,而不是编写单元测试,你应该编写集成测试.否则你只会对代码如何工作做出假设而没有证明它真正以这种方式工作.
在您的情况下,您的集成测试可能是控制器测试.您将使用Web测试客户端(由WebTestCase提供)调用URL,并验证在某些情况下您获得401或403响应.
PHPSpec是一种单元测试工具(又名设计工具).您需要使用其他东西编写集成测试(例如PHPUnit).我的项目通常至少安装了三个测试工具:
| 归档时间: |
|
| 查看次数: |
636 次 |
| 最近记录: |