简体   繁体   中英

symfony2 phpunit : how to drop and copy database before running tests?

In my symfony2 application, I am using phpunit to verify that the response from every route has a code 200.

Before I run the tests, I want to drop the test database and copy my production database under the name test (ie I want to reinitiate my test database).

I learned about the public static function setUpBeforeClass() but I am lost as to how drop and copy the database.

How can I do that ?

My class so far :

<?php

namespace AppBundle\Tests\Controller;

use AppBundle\FoodMeUpParameters;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

require_once __DIR__.'/../../../../app/AppKernel.php';


class ApplicationAvailabilityFunctionalTest extends WebTestCase
{

    public static function setUpBeforeClass()
    {

    }

    /**
     * @dataProvider routeProvider
     * @param $route
     */
    public function testAllRoutesAreLoaded($route)
    {
        $listedRoutes = $this->getListedRoutes();

        $this->assertArrayHasKey($route, $listedRoutes);
    }
}

This is some PHP code to back up a MySQL DB. The --routines includes your views, functions, stored proc, etc.

<?php
$schemaFile = "schema.sql";
$mysqlArgs  = "-u {$dbUser} -h {$dbHost} {$dbName}";

//if you don't have a pass and still pass in arg -p it will interrupt and prompt
if (isset($dbPassword) && strlen(trim($dbPassword)) > 0) { 
    $mysqlArgs .= " -p{$dbPassword}";
}

$mysqlDumpCommand = "mysqldump {$mysqlArgs} --routines";
$schemaDump       = "{$mysqlDumpCommand} > {$schemaFile}";
system($schemaDump);

Then the code to import it assuming same $mysqlArgs code as above.

$mysqlImportCommand = "mysql {$mysqlArgs}";
$import             = "{$mysqlImportCommand} < {$schemaFile}";
system($import);

My 5c. Usually you don't need to use setUpBeforeClass because it will populate DB for the whole suite and therefore create a risk of test dependency while unit tests must be independent. Use setUp and tearDown methods instead. Now to the point: you said you just want to test that response is code 200. Why would you want to populate the whole DB for that in the first place when you can simply mock expected responses from your models?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM