繁体   English   中英

测试Symfony中角色对控制器的访问

[英]Test roles access to controllers in symfony

我问自己如何在symfony角色访问中使用phpunit测试。 例如,如果我在安全配置中有一个indexAction和5个不同的角色,则我想确保用户A将具有401,用户B将具有403,用户C将具有500 ...

但这带来了一个问题:测试真的很久不能执行,因为我们有5个按功能进行的功能测试。

现在,我正在做这种事情:

/**
 * @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());
}

函数createClientWith验证我之前在dataProvider中定义的客户端。 它完全符合我之前的描述。

您是否知道如何做得更好(或至少要有更好的性能)?

谢谢!

取决于您的身份验证方法。 我使用JWT。 另外,我所有的Web测试都扩展了ApiTestCase,而ApiTestCase扩展了WebTestCase。 在所有WebTestCases中,我都使用登录用户。 记录使用方法在设置方法内登录。

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',
            )
        );
    }
}

这是一个测试示例:

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()
        );
    }
}

您的测试可能是

public function testRolesIndexAction($expectedCode)
{
    $this->client->request('GET', '/');

    $this->assertEquals($expectedCode, $this->client->getResponse()->getStatusCode());
}

尝试使用来一次调用$ this-> createClientWith。 我建议在这里寻求更多建议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM