Laravel 在测试时创建数据库

2022-01-08 00:00:00 php laravel laravel-4

我正在尝试运行我的单元测试并在安装过程中创建一个数据库.出于某种原因,我收到错误 Unknown database 'coretest'.如果我手动创建数据库并运行测试,那么我得到 Can't create database 'coretest';数据库存在.

I am trying to run my unit test and create a database during setup. For some reason I am getting the error Unknown database 'coretest'. If I create the database though manually and run the test then I get Can't create database 'coretest'; database exists.

drop database 语句现在只适用于 create database.

The drop database statement works just now the create database.

这是我的 setUP 和 tearDown 方法:

Here is my setUP and tearDown methods:

class TestCase extends IlluminateFoundationTestingTestCase {
    /**
     * Default preparation for each test
     */

    public function setUp() {
        parent::setUp();

        DB::statement('create database coretest;');
        Artisan::call('migrate');
        $this->seed();
        Mail::pretend(true);
    }

    public function tearDown() {
        parent::tearDown();
        DB::statement('drop database coretest;');
    }
}

推荐答案

你得到这个错误的原因仅仅是因为 laravel 试图连接到 config 中指定的数据库,该数据库不存在.

The reason why you get this error is simply because laravel tries to connect to database specified in config, which doesn't exist.

解决方案是在不指定数据库的情况下从设置中构建您自己的 PDO 连接(PDO 允许这样做)并使用它运行 CREATE DATABASE $dbname 语句.

The solution is to build your own PDO connection from the settings without specifying database (PDO allows this) and run CREATE DATABASE $dbname statement using it.

我们在项目中使用这种方法进行测试没有任何问题.

We used this approach for testing in our project without any problem.

这里一些代码:

<?php

/**
 * Bootstrap file for (re)creating database before running tests
 *
 * You only need to put this file in "bootstrap" directory of the project
 * and change "bootstrap" phpunit parameter within "phpunit.xml"
 * from "bootstrap/autoload.php" to "bootstap/testing.php"
 */

$testEnvironment = 'testing';

$config = require("app/config/{$testEnvironment}/database.php");

extract($config['connections'][$config['default']]);

$connection = new PDO("{$driver}:user={$username} password={$password}");
$connection->query("DROP DATABASE IF EXISTS ".$database);
$connection->query("CREATE DATABASE ".$database);

require_once('app/libraries/helpers.php');

// run migrations for packages
foreach(glob('vendor/*/*', GLOB_ONLYDIR) as $package) {
    $packageName = substr($package, 7); // drop "vendor" prefix
    passthru("./artisan migrate --package={$packageName} --env={$testEnvironment}");
}
passthru('./artisan migrate --env='.$testEnvironment);

require('autoload.php'); // run laravel's original bootstap file

相关文章