Skip to content

Instantly share code, notes, and snippets.

@shootacean
Created June 27, 2020 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shootacean/ac47d3b6d6136fe783abb4cd68ed5d6a to your computer and use it in GitHub Desktop.
Save shootacean/ac47d3b6d6136fe783abb4cd68ed5d6a to your computer and use it in GitHub Desktop.
CakePHP3のユニットテストでテストデータを動的に用意する方法
<?php
namespace App\Test\TestCase\Controller;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\TestCase;
class ArticlesControllerTest extends TestCase
{
public $Articles;
// 利用するテストデータを設定する
public $fixtures = ['app.Articles'];
public function testIndex()
{
$this->get('/articles/');
$this->assertResponceOk();
}
}
<?php
namespace App\Test\Fixture;
use App\Model\Table\ArticlesTable;
use Cake\Datasource\ConnectionManager;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\Fixture\TestFixture;
class ArticlesFixture extends TestFixture
{
// 開発用データベースを元にテスト用テーブルが作成されるようにする
public $import = ['table' => 'articles', 'connection' => 'local'];
public function init()
{
// 開発用データベースを使用する
$conn = ConnectionManager::get('local', false);
// 開発用データベースからデータを取得して、テストデータを作成する
$Articles = TableRegistry::getTableLocator()->get('Articles');
$articles = $Articles->setConnection($conn)->find()->toList();
$records = [];
foreach ($articles as $a) {
$records[] = [
'id' => $a->id,
'title' => $a->name,
];
}
$this->records = $records;
parent::init();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment