Symfony2: Creating Schema in PHPUnit only runs one

2019-06-11 15:34发布

问题:

I'm using Symfony2 and PHPUnit with Doctrine and writing a plugin bundle. I've got a TestCase class extending Symfony's WebTestCase.

During the setUp method, I need to create a schema for testing and load some fixtures.

My code (below) is building an app kernel, booting an application and then running several commands to drop a schema if it's there, re-create it and load some data fixtures.

The problem I'm getting is that when using the run() method on the Application, it's only running the first command, then the test stops, marking as successful with no errors or messages.

In order to execute the next command, I need to commend out the first one and run the test again.

Obviously, my desired result is for each method to run sequentially.

/**
 * setUp
 *
 * @return void
 **/
public function setUp()
{
    parent::setUp();

    $this->appKernel = $this->createKernel();
    $this->appKernel->boot();

    $this->application = new Application($this->appKernel);

    $this->em = $this->appKernel->getContainer()->get('doctrine')->getManager();

    $this->buildDb();
}

/**
 * buildDb
 * Builds the DB from the Entities in Acme\TestBundle\Entity
 * @return void
 **/
private function buildDb()
{
    $this->application->run(new ArrayInput(array(
        'doctrine:schema:drop',
        '--force' => true
    )));

    $this->application->run(new ArrayInput(array(
        'doctrine:schema:create'
    )));

    $this->application->run(new ArrayInput(array(
        'doctrine:fixtures:load',
        '--fixtures' => 'tests/SupportFiles/bundles/Acme/TestBundle/DataFixtures/Test'
    )));

}

回答1:

Just discovered how to stop this from happening.

The Application class by default, stops execution after a command is run. To stop it doing this, a method in Application must be called with 'false' passed as the argument:

$this->application->setAutoExit(false);


回答2:

I would encourage you to check out ICBaseTestBundle which can handle easily creating a clean database for each test case, and loading appropriate data fixtures, instead of writing your own version of doing it.