我們系統重構的時候,資料庫是有多個的,所以在 database.php 裡面定義了兩個 connections
'mysql' => [
'driver' => 'mysql',
'host' => env('MYSQL_HOSTNAME', 'localhost'),
'port' => env('MYSQL_PORT', 3306),
'database' => env('MYSQL_DATABASE', 'forge'),
'username' => env('MYSQL_USER', 'forge'),
'password' => env('MYSQL_PASSWORD', ''),
'charset' => env('MYSQL_CHARSET', 'utf8mb4'),
'collation' => env('MYSQL_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => env('MYSQL_PREFIX', ''),
'timezone' => env('MYSQL_TIMEZONE', '+08:00'),
'strict' => env('MYSQL_STRICT_MODE', true),
],
'new_mysql' => [
'driver' => 'mysql',
'host' => env('NEW_NEW_MYSQL_HOSTNAME', 'localhost'),
'port' => env('NEW_MYSQL_PORT', 3306),
'database' => env('NEW_MYSQL_DATABASE', 'forge'),
'username' => env('NEW_MYSQL_USER', 'forge'),
'password' => env('NEW_MYSQL_PASSWORD', ''),
'charset' => env('NEW_MYSQL_CHARSET', 'utf8mb4'),
'collation' => env('NEW_MYSQL_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => env('NEW_MYSQL_PREFIX', ''),
'timezone' => env('NEW_MYSQL_TIMEZONE', '+08:00'),
'strict' => env('NEW_MYSQL_STRICT_MODE', true),
]
很自然的,在 Model (表在 new_mysql 資料庫)裡面我們會覆蓋 connection
protected $connection = 'new_mysql';
這個時候測試出問題了,因為我的測試配置是:
database.php
'testing' => [
'driver' => 'sqlite',
'database' => ':memory:',
],
phpunit.xml
<env name="DB_CONNECTION" value="testing" />
因為 Model 裡面 connection 寫死了,所以在測試的時候會嘗試去連 new_mysql
正確的做法應該是在 Model 裡面透過覆蓋 getConnectionName 來處理 testing 的資料庫問題。
public function getConnectionName()
{
return app()->environment('testing') ? config('database.default') : 'new_mysql';
}
原文連結:https://www.lijinma.com/blog/2017/01/24/la...
本作品採用《CC 協議》,轉載必須註明作者和本文連結