我想检查具有访问控制的方法,例如,方法只授予特定的角色。因此,我知道在Symfony中有两种方式:
当涉及到单元测试时(对于我的案例phpspec,但我认为phpunit行为在这种情况下几乎是一样的),我想测试的是,只有匿名用户才能调用方法。第二,它很好用。在这里,我的设置:
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());
}
}在RegistrationHandler中,我有以下方法:
class RegistrationHandler
{
public function process()
{
$authorizationChecker = $this->get('security.authorization_checker');
if ($authorizationChecker->isGranted('ROLE_USER')) {
throw new AccessDeniedException();
}
// ...
}
}好吧,这种方法运行得很好--但通常,我更喜欢使用1.withSecurity注释(Sensio FrameworkExtraBundle),因此,它不起作用/我不知道为什么在作为注释编写时不会触发任何异常:
/**
* @Security("!has_role('ROLE_USER')")
*/
public function process()
{
// ...
}有人知道如何通过使用@Security注释的第一种方法来使这个示例工作,这是symfony推荐的更易读和更好的实践吗?
发布于 2016-02-26 09:32:15
在这两种情况下,您都在测试第三方代码( Symfony框架)提供的行为。遵循规则,不要嘲笑您不拥有的,而不是编写单元测试,而是应该编写集成测试。否则,您将只对代码的工作方式进行假设,而没有证据证明它确实是这样工作的。
在您的例子中,您的集成测试可能是一个控制器测试。您可以使用web测试客户端(由WebTestCase提供)调用URL,并验证在特定条件下您是否得到了401或403响应。
PHPSpec是一个单元测试工具(a.k.a )。(设计工具)。您需要使用其他工具(例如PHPUnit)编写集成测试。我的项目中通常至少安装了三个测试工具:
https://stackoverflow.com/questions/35579884
复制相似问题