在 Symfony 2.6 上用许多请求测试隔离

Test isolation with many requests on Symfony 2.6

我的项目使用 Symfony 2.6。我试图隔离我的测试,以免对我的数据库进行任何更改。

我设法通过一个请求隔离我的测试。但是当它们很多时,它不起作用,我无法找到原因。有什么想法吗?

这是我的测试控制器代码:

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class RequestControllerTest extends WebTestCase{

    protected $client;
    protected $entityManager;

    protected function setUp(){
        parent::setUp();
        $this->client = static::createClient();
        $this->entityManager = $this->client->getContainer()->get('doctrine')->getManager();
        $this->entityManager->beginTransaction();
    }

    protected function tearDown(){
        parent::tearDown();
        $this->entityManager->rollback();
        $this->entityManager->close();
    }

    // This test is working just fine : the request isn't deleted from database at the end
    public function testIsolationOK(){
       $this->client->request('DELETE', self::WEB_SERVICES_EXISTING_REQUEST_URL);
       $this->client->request('GET', self::WEB_SERVICES_EXISTING_REQUEST_URL);           
    }

    // But this one isn't working : the request is deleted from database at the end
    public function testIsolationNOK(){
       $this->client->request('GET', self::WEB_SERVICES_EXISTING_REQUEST_URL);
       $this->client->request('DELETE', self::WEB_SERVICES_EXISTING_REQUEST_URL);
    }

}

老实说,进行这种测试最简单和最安全的方法是创建一个新的数据库用于测试目的,并在 config_test.yml.

中指定其配置

使用这种方法,您将确保您的真实数据库没有被测试修改的危险,并且还会使您在测试时更轻松。

我通常使用这种方法,但我不知道它是否是您想要的。

Documentation

希望对您有所帮助。

我终于设法让它以这种方式工作:

public function testIsolationOK(){
   $this->client->request('GET', self::WEB_SERVICES_EXISTING_REQUEST_URL);
   $this->setUp();
   $this->client->request('DELETE', self::WEB_SERVICES_EXISTING_REQUEST_URL);
}

我不知道这样做是否正确,但它确实有效。 作为提醒,这里是 setUp 方法:

protected function setUp(){
    parent::setUp();
    $this->client = static::createClient();
    $this->entityManager = $this->client->getContainer()->get('doctrine')->getManager();
    $this->entityManager->beginTransaction();
}