背景
[https://qiita.com/ucan-lab/items/c1fcc4ed6db525f083fb:embed:cite]
-
Laravel フレームワークにて、PHPUnitのdataProvider内でFacadeやfactoryが使えないのはよく知られている通り
parent::setUp()
の中で$this->createApplication()
される前にFacadeやfactoryを呼び出すとエラー- ver 6.0で解消されたっぽい
[https://blog.martinhujer.cz/how-to-use-data-providers-in-phpunit/:embed:cite]
- ↑の記事から着想を得て、遅延評価でこれを回避してみる
テストコード
<?php
declare(strict_types=1);
namespace Tests\Unit;
use App\User;
use Hash;
use Tests\TestCase;
class FacadeTest extends TestCase
{
/**
* @test
* @dataProvider dataProvider_dame
*/
public function dame($user, $hash): void
{
$this->assertNotNull($user);
$this->assertNotNull($hash);
}
/**
* @test
* @dataProvider dataProvider_lazy
*/
public function ok(callable $user, callable $hash): void
{
$this->assertNotNull($user());
$this->assertNotNull($hash());
}
// ----------------------------------------
// dataProviders
// ----------------------------------------
/**
* @return iterable
*/
public function dataProvider_dame(): iterable
{
yield [
'user' => factory(User::class)->make(),
'hash' => Hash::make('secret'),
];
}
/**
* @return iterable
*/
public function dataProvider_lazy(): iterable
{
yield [
'user' => function () {
return factory(User::class)->make();
},
'hash' => function () {
return Hash::make('secret');
},
];
}
}
実行結果
遅延評価じゃない方: ダメ
bash-4.4# ./vendor/bin/phpunit tests/Feature/LazyDataProviderTest.php --filter=dame
PHPUnit 7.5.15 by Sebastian Bergmann and contributors.
W 1 / 1 (100%)
Time: 290 ms, Memory: 4.00 MB
There was 1 warning:
1) Warning
The data provider specified for Tests\Unit\FacadeTest::dame is invalid.
Unable to locate factory with name [default] [App\User].
WARNINGS!
Tests: 1, Assertions: 0, Warnings: 1.
- データプロバイダー内でエラー出てWarningに
遅延評価: OK
bash-4.4# ./vendor/bin/phpunit tests/Feature/LazyDataProviderTest.php --filter=ok
PHPUnit 7.5.15 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 995 ms, Memory: 8.00 MB
OK (1 test, 2 assertions)
やったあ