Build testing data into SQLite

531人参与 |来源: |时间:2020-05-21
Build testing data into SQLite with Seed

在写测试之前,通常都会先準备好测试资料库,但当架构一複杂,準备测资反而旷日废时,透过 Laravel MigratSeed机制,并将测资写进 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(){// 动态修改设定,改接上 SQLiteconfig(['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// 清除所有 migrateArtisan::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


分类 AndroidAngularJSChromeDatabaseMySQLDataStructureEditorVimFirefoxGitHadoopLanguageGoJavaJavaScriptjQueryjQueryChartNode.jsVuePHPLaravelZendFrameworkPythonMacNetworkCiscoDLinkJuniperOauthServerApacheShareUnixFreeBSDLinuxWebDesignBootstrapCSSHTMLWordpressSearch搜寻:sqliteartisanusephpfunctionseed测资databasetestcasemember测试laravelmigrate
上一篇:
下一篇: