2017-08-28 64 views
0

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

但它会导致一个问题:测试需要很长的时间才能执行,因为我们有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验证,我在我的数据提供程序之前定义的客户端。它正是我之前描述的。

你对于如何做得更好或者 - 至少 - 有更好的表现吗?

谢谢!

+0

你可以异步执行你的测试/并行,加快整体执行时间。 – nifr

回答

0

尝试使用this来调用一次$ this-> createClientWith。我建议看看here了解更多建议。

1

取决于您的验证方法。我使用JWT。另外,我所有的Web测试都扩展了扩展WebTestCase的ApiTestCase。在所有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()); 
}