Zi 字媒體
2017-07-25T20:27:27+00:00
Build testing data into SQLite with Seed
PHP:7.2
Laravel:5.8
PHPUnit:7.5.6
在寫測試之前,通常都會先準備好測試資料庫,但當架構一複雜,準備測資反而曠日廢時,透過 Laravel Migrat 跟 Seed機制,並將測資寫進 SQLite,可以讓測試變得更輕鬆。
Config
首先,先針對 tests/TestCase.php 這支 Laravel 中主要的測試類別進行調整,將其加入資料庫及匯入測資的設定。
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\Artisan;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected function initDatabase()
{
// 動態修改設定,改接上 SQLite
config([
'database.default' => 'sqlite',
'database.connections.sqlite' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
]);
// 呼叫 php artisan migrate 建立 table
// 呼叫 php artisan db:seed 匯入測試資料
Artisan::call('migrate');
Artisan::call('db:seed');
}
protected function resetDatabase()
{
// php artisan migrate:reset
// 清除所有 migrate
Artisan::call('migrate:reset');
}
}
Test Case
在基本設定完成以後,我們只要在每次測試時,呼叫匯入測資的 method 就可以輕鬆將測資準備好了。
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Models\Member;
class MemberTest extends TestCase
{
public function setUp(): void
{
// 呼叫父類別的 setUp()
parent::setUp();
$this->initDatabase();
}
public function tearDown(): void
{
$this->resetDatabase();
// 呼叫子類別的 tearDown()
parent::tearDown();
}
public function testBasicTest()
{
$member = Member::first();
$this->assertEquals(1, $member->id);
}
}
Categories: Laravel
Tags: LaravelPHP
分類
Android
AngularJS
Chrome
Database
MySQL
DataStructure
Editor
Vim
Firefox
Git
Hadoop
Language
Go
Java
JavaScript
jQuery
jQueryChart
Node.js
Vue
PHP
Laravel
ZendFramework
Python
Mac
Network
Cisco
DLink
Juniper
Oauth
Server
Apache
Share
Unix
FreeBSD
Linux
WebDesign
Bootstrap
CSS
HTML
Wordpress
Search
搜尋:
寫了
5860316篇文章,獲得
23313次喜歡