Symfony2测试数据库生产环境

时间:2013-02-01 08:03:46

标签: testing symfony doctrine

在生产服务器上的每次代码更新之前,我通过在测试数据库中插入行来执行phpunit测试。 由于测试数据库不反映生产数据库的内容,我想在生产数据库上执行测试。 测试完成后,我想在测试期间删除所有创建的行。实现这一目标的最佳方法是什么? 我无法想到一种完全没法的方法,也没有改变生产数据的风险。

2 个答案:

答案 0 :(得分:1)

我使用Alexandre Salome在Isolation of tests in Symfony2中描述的方法将我的测试与事务和回滚隔离开来。这种方法非常有效,但显然你要在生产数据库上使用它之前要彻底测试它!

答案 1 :(得分:0)

我建议您使用sqlite(默认)进行测试,因为它更快,您不必担心它们是否会在生产数据库上搞砸。我做的是每一个

EntityTest.php extends TestsHelper.php extends PHPUnit_Framework_TestCase

在setup()中,我创建数据库和灯具。

我从互联网上获取代码并且有效。你可能会发现它很有用。

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