简体   繁体   English

symfony2 phpunit:如何在运行测试之前删除并复制数据库?

[英]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. 在我的symfony2应用程序中,我使用phpunit来验证每个路由的响应是否有代码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). 在我运行测试之前,我想删除测试数据库并在名称test下复制我的生产数据库(即我想重新启动我的测试数据库)。

I learned about the public static function setUpBeforeClass() but I am lost as to how drop and copy the database. 我了解了public static function setUpBeforeClass()但我丢失了如何删除和复制数据库。

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. 这是备份MySQL数据库的一些PHP代码。 The --routines includes your views, functions, stored proc, etc. --routines包括你的视图,函数,存储过程等。

<?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. 然后导入它的代码假设与上面相同的$mysqlArgs代码。

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

My 5c. 我的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. 通常,您不需要使用setUpBeforeClass因为它将为整个套件填充DB,因此会产生测试依赖性的风险,而单元测试必须是独立的。 Use setUp and tearDown methods instead. 请改用setUptearDown方法。 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? 现在到了这一点:你说你只想测试那个响应是代码200.当你只是模拟模型的预期响应时,你为什么要首先填充整个数据库?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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