psylo66
psylo66

Reputation: 628

Load fixtures one time before all phpunit test on symfony 3

I ve got a SF3 application and lot of functionnals tests. Before each tests we load and purge all fixtures. Time of all tests are so long. I would like to load fixtures just one time et truncate after last test.

Is it the good method to improve functionnal tests speed ?

Is there a php method in phpunit which is launched just one time before all tests ? (Because setUpBeforeClass is executed before each test)

An exemple of the setUpBeforeClass method in my test's classes.

class SearchRegisterControllerTest extends WebTestCase
{
    /** @var Client $client */
    private $client;

    protected static $application;

    public static function setUpBeforeClass()
    {
        $kernel = static::createKernel();
        $kernel->boot();

        $em = $kernel->getContainer()->get('doctrine.orm.entity_manager');
        $schemaTool = new SchemaTool($em);
        $metadata = $em->getMetadataFactory()->getAllMetadata();

        $schemaTool->dropSchema($metadata);
        $schemaTool->createSchema($metadata);

        /** @var Client $client */
        $client = static::createClient();
        $em = $client->getContainer()->get('doctrine.orm.entity_manager');

        $loader = new Loader();

        $loader->loadFromDirectory('src/MyNameSpace/AppBundle/DataFixtures/ORM');

        $purger = new ORMPurger();
        $executor = new ORMExecutor($em, $purger);
        $executor->execute($loader->getFixtures(), true);

    }

Thanks in advance.

Upvotes: 5

Views: 3710

Answers (2)

Matteo
Matteo

Reputation: 39410

You could implement a test listener.

tests/StartTestSuiteListener.php

namespace App\Tests;



class StartTestSuite extends \PHPUnit_Framework_BaseTestListener
{
    public function startTestSuite(\PHPUnit_Framework_TestSuite $suite)
    {
      // do initial stuff
    }

}

Then enable enable the test listener in your phpunit.xml config:

phpunit.xml

<phpunit
 ...
>
    <listeners>
        <listener class="App\Tests\StartTestSuiteListener">
        </listener>
    </listeners>
[...]
</phpunit>

In the same manner you could implement a endTestSuite (Check for all event listed in the doc)

Hope this help

Upvotes: 4

svgrafov
svgrafov

Reputation: 2014

You can use bash script like this to load fixtures once before all tests.

php bin/console doctrine:database:create --env=test --if-not-exists
php bin/console doctrine:schema:update --force --env=test --complete
php bin/console doctrine:fixtures:load --fixtures=tests/fixtures/api --env=test --no-interaction
php vendor/bin/phpunit tests/Functional

Keep in mind that your test will not be executed within isolated environments with fresh data and thus will interfere with each other.

Upvotes: 2

Related Questions