Laravel unit test dataProvider で変数やconfig 使う場合
コードとコメントで全部表してますがこんな感じ。
unitテストにしろFeatureテストにしろ、データプロバイダを使って、test用の配列データを作るというのは良くやるかと思いますが、 unitテストで データプロバイダ使う際には、
$this->createApplication();
というのを最初に書いてやらないと駄目らしいです。(laravel6系で確認)
/**
* データプロバイダ
* @return array
*/
public function hogeParams()
{
// unitTestでは DataProviderにこれが必要
$this->createApplication();
// 上のを入れないとdataProvider内でこんなのが使えなくなる
$otherId = config('const.hoge-id');
// この辺にTestで使う配列を記述
return [
// 配列宣言
];
}
$this->createApplication();を書かないとこんな風に怒られる
There was 1 warning: 1) Warning The data provider specified for Tests\Feature\HogeTest::postValidateRequiredIfTest is invalid. Target class [config] does not exist. WARNINGS! Tests: 1, Assertions: 0, Warnings: 1.
追記:
ノウハウとして、$this->createApplication();とだけ書けば良い。という理解でもいいのだけど、これ、実は
Laravelのtestsディレクトリにある以下のメソッドを呼んでいるってことですね。
\tests\CreatesApplication.php
<?php namespace Tests; use Illuminate\Contracts\Console\Kernel; trait CreatesApplication { /** * Creates the application. * * @return \Illuminate\Foundation\Application */ public function createApplication() { $app = require __DIR__.'/../bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); return $app; } }
これ、確かLaravel自体をアプリケーションとまず動かす奴で index.php とかから追える処理で書いている事と基本は同じですね。つまり unit test単体として完結した ピュアなphpunit 環境でtestさせるんじゃなくて、laravelとして動かして動作検証するというか、そんな感じ。 詳しく追ってないけど DataProvider という機能自体がLaravel固有のものなのかな?そんな気がする。