【发布时间】:2021-07-18 12:24:07
【问题描述】:
我正在尝试在 laravel 7.x 中进行单元测试。
我创建了一个测试数据库,该数据库与我用于我的网站的数据库相同。
我修改了 phpunit.xml 文件,我创建了一个 .env.testing 文件并添加了一个到 database.php 文件,但我得到一个 "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cbs_perform_test.cbs_defis' doesn't exist (SQL: select count(*) as aggregate from cbs_defis )" 错误。
我已经多次检查了数据库和表的名称,以确保我使用的是正确的。
我已经遵循了这些指南:Use different database for testing and local; How to Specify a Separate Database for Unit Testing on Laravel 5
这是我的 phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true">
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<server name="APP_ENV" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="DB_CONNECTION" value="testing"/>
<server name="DB_DATABASE" value="cbs_perform_test"/>
<server name="MAIL_MAILER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
<env name="DB_CONNECTION" value="testing"/>
</php>
我的 database.php 连接
'testing' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => false,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
我的 .env.testing 文件
APP_ENV=testing
DB_CONNECTION=testing
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cbs_perform_test
DB_USERNAME=root
DB_PASSWORD=
我的测试代码
class DefiTest extends TestCase
{
use DatabaseMigrations;
use DatabaseTransactions;
/**
* A basic unit test example.
*
* @return void
*/
public function testCreateDefi()
{
$request = new Request();
$request->DEF_NOM = 'test';
$request->DEF_DESCRIPTION = 'testdescriptio ajhsg ln';
$request->DEF_NBSEMAINES = 2;
$request->DEF_CONSEILS = 'jhasnciu launh sl';
$request->DEF_VISIBLE = 1;
$request->DEF_DATE_VISIBLE = Carbon::now()->toDate();
$request->COA_ID = 3;
$dfc = new DefiCoachController();
$response = $dfc->createDefiTest($request);
$this->assertDatabaseHas('cbs_defis', $request->all());
}
}
我用于测试的命令:php artisan test --env=testing
【问题讨论】: