使用phpunit模拟symfony安全性,返回null值而不是bool(不使用预言)



我有一个验证器,它调用symfony安全组件的多个方法。

我用phpunit来嘲笑它。getUser工作得很好,但我似乎不能用isGranted返回布尔值。它仅适用于willReturn(true)

如果我使用will($this->returnValueMap($map)),它会说:TypeError: Return value of Mock_Security_ccdbfb27::isGranted() must be of the type bool, null returned

如果我使用willReturn($this->returnValueMap($map)),我得到:Method isGranted may not return value of type PHPUnitFrameworkMockObjectStubReturnValueMap, its return declaration is ": bool"

如果我尝试使用回调,也会出现同样的问题。

private function getValidator(string $loggedUserRole, bool $expectsViolation)
{
$map = [
['ROLE_ADMIN', $loggedUserRole === 'ADMIN'],
['ROLE_MANAGER', ($loggedUserRole === 'ADMIN' || $loggedUserRole === 'MANAGER')],
];
$security = $this->createMock(Security::class);
$security
->method('getUser')
->willReturn($loggedUserRole === 'ANONYMOUS'? null : (new User()));
$security
->expects($this->any())
->method('isGranted')
->will($this->returnValueMap($map));
$validator = new ValidatorClass($security);
$context = $this->getContext($expectsViolation);
$validator->initialize($context);
return $validator;
}

我遇到了类似的问题。

"isGranted"方法的第二个输入参数(subject(默认为"null"。您必须将其作为第二个值包含在参数映射中,第三个值将作为结果。

所以在你的情况下:

$map = [
['ROLE_ADMIN', null,  $loggedUserRole === 'ADMIN'],
['ROLE_MANAGER', null, ($loggedUserRole === 'ADMIN' || $loggedUserRole === 'MANAGER')],
];

最新更新