Created
June 27, 2020 15:49
-
-
Save shootacean/ac47d3b6d6136fe783abb4cd68ed5d6a to your computer and use it in GitHub Desktop.
CakePHP3のユニットテストでテストデータを動的に用意する方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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