フィクスチャ
フィクスチャ
テストコードの挙動がデータベースやモデルに依存するとき、テストに使うためのテーブルを生成し、 一時的なデータをロードするために フィクスチャを使うことができる。
- フィクスチャを使うことにより、 実際のアプリケーションに使われているデータを破壊することなくテストができる。
- アプリケーションのためのコンテンツを実際に用意するより先にコードをテストすることができる。
CakePHP はフィクスチャーに基づいたテストケースを実行するにあたり、以下の動作をする。
- 各フィクスチャーで必要なテーブルを作成する
- フィクスチャーにデータが存在すれば、それをテーブルに投入する
- テストメソッドを実行
- フィクスチャーのテーブルを空にする
- データベースからフィクスチャーのテーブルを削除する
フィクスチャの作成
Articleモデルのフィクスチャを作成する場合、tests/FixtureディレクトリにArticlesFixture.phpという名前のファイルを作成する。
フィクスチャクラスにはCake\TestSuite\Fixture\TestFixture
を継承させる。
<?php namespace App\Test\Fixture; use Cake\TestSuite\Fixture\TestFixture; class ArticlesFixture extends TestFixture { // オプション。異なるテストデータソースにフィクスチャーをロードするために、このプロパティーを設定 public $connection = 'test'; public $fields = [ 'id' => ['type' => 'integer'], 'title' => ['type' => 'string', 'length' => 255, 'null' => false], 'body' => 'text', 'published' => ['type' => 'integer', 'default' => '0', 'null' => false], 'created' => 'datetime', 'modified' => 'datetime', '_constraints' => [ 'primary' => ['type' => 'primary', 'columns' => ['id']] ] ]; public $records = [ [ 'title' => 'First Article', 'body' => 'First Article Body', 'published' => '1', 'created' => '2007-03-18 10:39:23', 'modified' => '2007-03-18 10:41:31' ], [ 'title' => 'Second Article', 'body' => 'Second Article Body', 'published' => '1', 'created' => '2007-03-18 10:41:23', 'modified' => '2007-03-18 10:43:31' ] ]; }
$connection
フィクスチャーが使用するデータソースを定義する。上の例ではデフォルトの test データソースを使用している。
$fields
テーブルを構成するフィールドと、その定義を記述する。
オプション
- type: データ型を指定
- length: 文字列の長さを指定
- null: null許容(true or false)を指定
- default: デフォルト値を指定
- precision: 小数点以下の桁数を指定
フィクスチャのロード
<?php class ArticlesTest extends TestCase { public $fixtures = ['app.Articles', 'app.Comments']; }
上の例ではArticlesフィクスチャとCommentsフィクスチャをロードしている。