[英]Test roles access to controllers in symfony
I'm asking myself how to tests with phpunit in symfony roles access. 我问自己如何在symfony角色访问中使用phpunit测试。 For example, if i have an indexAction and 5 different roles in my security config, i want to be sure that user A will have a 401, user B a 403, user C a 500...
例如,如果我在安全配置中有一个indexAction和5个不同的角色,则我想确保用户A将具有401,用户B将具有403,用户C将具有500 ...
But it cause an issue: tests are really long to execute, because we have 5 functional tests by action. 但这带来了一个问题:测试真的很久不能执行,因为我们有5个按功能进行的功能测试。
Now, i'm doing that kind of thing: 现在,我正在做这种事情:
/**
* @covers \App\Bundle\FrontBundle\Controller\DefaultController::indexAction()
*
* @dataProvider rolesAllAccess
*
* @param string $user
* @param integer $expectedCode
*
* @return void
*/
public function testRolesIndexAction($user, $expectedCode)
{
$client = $this->createClientWith($user);
$client->request('GET', '/');
$this->assertEquals($expectedCode, $client->getResponse()->getStatusCode());
}
The function createClientWith authenticate a client that i have defined in my dataProvider before. 函数createClientWith验证我之前在dataProvider中定义的客户端。 It makes exactly what i described before.
它完全符合我之前的描述。
Do you have any idea on how doing that better or - at least - with better performances ? 您是否知道如何做得更好(或至少要有更好的性能)?
Thanks! 谢谢!
Depends on your authentication method. 取决于您的身份验证方法。 I use JWT.
我使用JWT。 Also, all my web tests extends ApiTestCase that extends WebTestCase.
另外,我所有的Web测试都扩展了ApiTestCase,而ApiTestCase扩展了WebTestCase。 And In all WebTestCases I use a logged user.
在所有WebTestCases中,我都使用登录用户。 Logged use log in inside the setup method.
记录使用方法在设置方法内登录。
abstract class ApiTestCase extends WebTestCase
{
protected function setUp()
{
$client = static::makeClient();
$client->request(
'POST',
'/tokens', [
'username' => 'username',
'password' => 'password'
], [
// no files here
],
$headers = [
'HTTP_CONTENT_TYPE' => 'application/x-www-form-urlencoded',
'HTTP_ACCEPT' => 'application/json',
]
);
$response = $client->getResponse();
$data = json_decode($response->getContent(), true);
$this->client = static::createClient(
array(),
array(
'HTTP_Authorization' => sprintf('%s %s', 'Bearer', $data['token']),
'HTTP_CONTENT_TYPE' => 'application/json',
'HTTP_ACCEPT' => 'application/json',
)
);
}
}
And here an example of test: 这是一个测试示例:
class DivisionControllerTest extends ApiTestCase
{
public function testList()
{
$this->client->request('GET', '/resource');
$response = $this->client->getResponse();
$expectedContent = ' !!! put expected content here !!! ';
$this->assertEquals(
$expectedContent,
$response->getContent()
);
}
}
Your test could be 您的测试可能是
public function testRolesIndexAction($expectedCode)
{
$this->client->request('GET', '/');
$this->assertEquals($expectedCode, $this->client->getResponse()->getStatusCode());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.