How can I re-create my database in PHP (for example, for unit testing)

How can I re-create my database with PHP, perhaps by inserting default data. Currently, I intend to use the behavior for Unit Tests.

I use Doctrine 2, Zend Framework 1.11, Zend_Test for unit tests

I could use the CLI

 doctrine orm:schema-tool:update --force 

Or

 doctrine orm:schema-tool:drop --force doctrine orm:schema-tool:create 

I'm looking for a replacement for PHP so far found this

but it will look something like

 $tool = new \Doctrine\ORM\Tools\SchemaTool($em); $classes = array( $em->getClassMetadata('Entities\User'), $em->getClassMetadata('Entities\Profile') ); $tool->dropSchema($classes, \Doctrine\ORM\Tools\SchemaTool::DROP_DATABASE); $tool->createSchema($classes); 

And I really do not want to specify model classes, esp in development, when they can change. It should just read from all the classes listed in ... below ... just like with the CLI, do you need to specify the classes you need?

 $driverImpl = $config->newDefaultAnnotationDriver(array(realpath('../models'))); $config->setMetadataDriverImpl($driverImpl); 
+7
source share
3 answers

you can use

The PHPUnit extension for Doctrine offers several hooks to the PHPUnits database extension and offers a very convenient way to test your Doctrine 2 code against the database.

There are several examples in the Readme, including an example that shows how to create an on-the-fly database schema. Benjamin Eberlay is the main donor of the doctrine.

Also see B. Eberlei Ultimate Guide for Testing a Database Using PHPUnit

+5
source

Since you set the model path when setting up the EntityManager, you can create a circuit in the code without having to reuse this path (and without declaring each class). To do this, you need to get a link to your configured EntityManager instance and get a link to ClassMetadataFactory, which you can then call ClassMetadataFactory # getAllMedata ().

Here is an example where I have a static Bootstrap class that allows me to get a link to the EntityManager from anywhere, and I recreate the setUp () call scheme in unit tests:

 class ModelTestCase extends PHPUnit_Framework_TestCase { public function setUp() { $em = Bootstrap::getEntityManager(); $tool = new \Doctrine\ORM\Tools\SchemaTool($em); $mdFactory = $em->getMetadataFactory(); $tool->createSchema($mdFactory->getAllMetadata()); parent::setUp(); } } 
+1
source

Doctrine supports fixtures . Give it a try.

0
source

All Articles