2013-02-01 128 views
1

在生產服務器上的每次代碼更新之前,我通過在測試數據庫中插入行來執行phpunit測試。 由於測試數據庫不能反映生產數據庫的內容,因此我想對生產數據庫執行測試。 測試完成後,我想在測試過程中刪除所有創建的行。什麼是實現這一目標的最佳方式? 我無法想象一種完美的方法,無需更改生產數據。Symfony2測試數據庫生產環境

回答

1

我使用Alexandre Salome在Isolation of tests in Symfony2中描述的方法來隔離我的測試和事務並在最後回滾。這種方法工作得很好,但顯然你需要在生產數據庫上使用它之前仔細測試它!

+0

的偉大工程!謝謝 ! –

0

我建議你使用sqlite(默認)進行測試,因爲它更快,你不必擔心他們是否會在生產數據庫上搞點東西。我所做的是每個

EntityTest.php extends TestsHelper.php extends PHPUnit_Framework_TestCase

和設置(),我創建的數據庫和燈具。

我從互聯網上的代碼,它的工作原理。你可能會覺得它很有用。

// class TestsHelper 

/** 
* @var Symfony\Component\DependencyInjection\Container 
*/ 
protected $container; 

public function setUp() 
{ 
    // Boot the AppKernel in the test environment and with the debug. 
    $this->kernel = new \AppKernel('test', true); 
    $this->kernel->boot(); 

    // Store the container and the entity manager in test case properties 
    $this->container = $this->kernel->getContainer(); 
    $this->em = $this->container->get('doctrine')->getEntityManager(); 

    // Build the schema for sqlite 
    $this->generateSchema(); 

    $this->generateFixtures() ; 

    parent::setUp(); 
} 

public function tearDown() 
{ 
    // Shutdown the kernel. 
    $this->kernel->shutdown(); 

    parent::tearDown(); 
} 

protected function generateSchema() 
{ 
    // Get the metadatas of the application to create the schema. 
    $metadatas = $this->getMetadatas(); 

    if (! empty($metadatas)) { 
     // Create SchemaTool 

     /** 
     * @var \Doctrine\ORM\Tools\SchemaTool 
     */ 
     $tool = new SchemaTool($this->em); 
//   $tool->dropDatabase() ; 
     $tool->createSchema($metadatas); 
    } else { 
     throw new Doctrine\DBAL\Schema\SchemaException('No Metadata Classes to process.'); 
    } 
} 
/** 
* Overwrite this method to get specific metadatas. 
* 
* @return Array 
*/ 
protected function getMetadatas() 
{ 
    return $this->em->getMetadataFactory()->getAllMetadata(); 
} 

而且在generateFixtures(),您將創建他們像往常一樣:

$entity = new MyEntity() ; 
$this->em->persist($entity) ; 
$this->em->flush() ; 
+0

謝謝,但我想對生產數據庫執行測試 –

相關問題