代码之家  ›  专栏  ›  技术社区  ›  emottet

在Symfony 2.6上测试多个请求的隔离

  •  0
  • emottet  · 技术社区  · 11 年前

    我的项目使用Symfony 2.6。我正在尝试隔离我的测试,以便不在我的数据库上提交任何更改。

    我只需要一个请求就可以隔离我的测试。但是当有很多这样的时候,它就不起作用了,我也找不到原因。有什么想法吗?

    这是我的testController代码:

    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);
        }
    
    }
    
    2 回复  |  直到 11 年前
        1
  •  1
  •   acontell    11 年前

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

    使用这种方法,您可以确保您的真实DB不会受到测试修改的危险,并且在测试时也会使您的生活更轻松。

    我通常使用这种方法,尽管我不知道这是否是你想要的。

    Documentation

    希望有帮助。

        2
  •  0
  •   emottet    11 年前

    我终于设法做到了:

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