privateの静的関数をPHPUnitでテストする
PHPUnitでの private static function
のテスト方法がわからなかったのでメモ。
公式のドキュメントを見るとReflectionMethod::invokeArgs
に最初の引数にnullを渡してあげればよさそうなのでやってみる。
PHPUnitをインストールする
$ composer require phpunit/phpunit --dev
privateの静的関数を含んだテスト対象のクラスを作成する
<?php class Hoge { private static function fuga() { return 'hello'; } }
PHPUnitのテストを書く
<?php use PHPUnit\Framework\TestCase; require_once 'Hoge.php'; class HogeTest extends TestCase { /** * privateの静的関数fugaのテスト */ public function test_fuga() { $expected = 'hello'; $class = new \ReflectionClass(new Hoge()); $method = $class->getMethod('fuga'); $method->setAccessible(true); // 第一引数にnullを渡すとstaticメソッドが呼べる $actual = $method->invokeArgs(null, []); $this->assertEquals($expected, $actual); } }
テストを実行する
$ phpunit HogeTest.php PHPUnit 6.5.5 by Sebastian Bergmann and contributors. . 1 / 1 (100%) Time: 65 ms, Memory: 10.00MB OK (1 test, 1 assertion)